<?php

namespace control;
/*
*新增凭证类
*/

class voucherEditClass extends adIndexClass
{
    private const page = 'voucherEdit';
    private const table = 'voucher';
    private const table_mx = 'voucher_detail';
    private const title = '新增凭证';
    public string $addIco = root . 'img/control/list_add.svg';//添加行
    public string $delIco = root . 'img/control/del-light-blur.svg';//删除行
    public string $printIcon = root . 'img/control/print-white.svg';//打印
    public string $copyIcon = root . 'img/control/list_copy.svg';//复制
    public string $useTemplateIcon = root . 'img/control/template_use.svg';//使用模板
    public string $keyboardIcon = root . 'img/control/keyboard.svg';//快捷键
    public string $leftIco = root . 'img/control/pre.svg';//上一张
    public string $leftIcoGray = root . 'img/control/pre-gray.svg';//没有上一张
    public string $rightIcon = root . 'img/control/next.svg';//下一张
    public string $rightIconGray = root . 'img/control/next-gray.svg';//没有下一张
    public string $shortcutImg = root . 'img/control/shortcut.png';//快捷键显示图
    public string $settingIcon = root . 'img/control/setting-blue.svg';//设置图标
    public array $typeOption = ['redChong' => '红冲', 'salary' => '工资凭证', 'endPeriod' => '期末结转', 'insert' => '插入', 'template' => '复制'];

    /*列表-查询条件*/
    public function home()
    {
        return $this->room();
    }

    /**
     * 数量保留位数
     * @return int
     */
    public static function numDecimal(): int
    {
        $setting = optionSettingClass::getSetting('总账');
        return $setting['invoicePrice'] ?? 4;
    }

    /**
     * 单价保留位数
     * @return int
     */
    public static function priceDecimal(): int
    {
        $setting = optionSettingClass::getSetting('总账');
        return $setting['invoicePrice'] ?? 4;
    }

    /**
     * 单价格式化
     * @param $price
     * @return float
     */
    public static function formatPrice($price): float
    {
        return round($price ?: 0, self::priceDecimal());
    }

    /**
     * 数量格式化
     * @param $num
     * @return float
     */
    public static function formatNum($num): float
    {
        return round($num ?: 0, self::numDecimal());
    }

    /**
     * 舍零
     * @param $value
     * @param int $type
     * @return float
     */
    public static function formatZero($value, $type = 1): float
    {
        $setting = optionSettingClass::getSetting('总账');
        if ($type == 1) {
            //数量
            $setting['numPrecision']['numLostZero'] = $setting['numPrecision']['numLostZero'] ?? '';
            if ($setting['numPrecision']['numLostZero']) {
                $value = floatval($value);
            }

        } elseif ($type == 2) {
            //单价
            $setting['pricePrecision']['priceLostZero'] = $setting['pricePrecision']['priceLostZero'] ?? '';
            if ($setting['pricePrecision']['priceLostZero']) {
                $value = floatval($value);
            }
        }
        return floatval($value);
    }


    /**
     * 凭证号
     * @param $voucherWordId
     * @param $recordDate
     * @param int $num
     * @return int
     */
    public static function voucherNo($voucherWordId, $recordDate, $num = 1): int
    {
        if (!$voucherWordId || !$recordDate) {
            return 1;
        }
        $month = date('Y-m', strtotime($recordDate));
        $last  = query(self::table, "coid = '" . self::$coid . "' and isTemplate='否' and voucherWordId = '$voucherWordId' and date_format(recordDate,'%Y-%m') = '$month' order by voucherNo desc");
        if (empty($last['id'])) {
            $voucherNo = $num;
        } else {
            $voucherNo = $last['voucherNo'] + $num;
        }
        return $voucherNo;
    }

    /**
     * 判断是否有辅助核算
     */
    public function assistAccountJuage($subject, $index, $mxId, $array)
    {
        if ($subject['assistAccount'] == '是') {
            $assistAccount = explode(',', $subject['assistAccountIds']);
            foreach ($assistAccount as $type) {
                $objId = match ($type) {
                    '客户' => 'khid',
                    '员工' => 'staffId',
                    '部门' => 'departmentId',
                    '项目' => 'projectId',
                    '现金流' => 'cashId',
                    '供应商' => 'supplierId',
                    '存货' => 'materialId',
                };
                if ($array['subjectId'][$mxId] && empty($array[$objId][$mxId])) {
                    return "第" . ($index) . "行辅助核算未填写完整";
                }
            }
        }
        return true;
    }


    /**
     * 编辑
     */
    public function editEdit()
    {
        $href          = $this->get('href');
        $source        = $this->post('source');
        $id            = $this->post('id') ?: self::getId();
        $subjectIds    = $this->post('subjectId');
        $cashIds       = $this->post('cashId');
        $khids         = $this->post('khid') ?: [];
        $supplierIds   = $this->post('supplierId') ?: [];
        $staffIds      = $this->post('staffId') ?: [];
        $projectIds    = $this->post('projectId') ?: [];
        $departmentIds = $this->post('departmentId') ?: [];
        $materialIds   = $this->post('materialId') ?: [];
        $voucherNums   = $this->post('voucherNum') ?: [];
        $voucherPrices = $this->post('voucherPrice') ?: [];
        $voucherRates  = $this->post('voucherRate') ?: [];
        $jieMoneys     = $this->post('jieMoney');
        $daiMoneys     = $this->post('daiMoney');
        $summarys      = $this->post('summary');
        $mxIds         = $this->post('mxId');
        $currencyIds   = $this->post('currencyId');
        $sourceId      = $this->post('sourceId');//来源ID
        $field         = [
            'recordDate'    => $this->post('recordDate'),
            'voucherWordId' => $this->post('voucherWordId'),
            'receiptNum'    => $this->post('receiptNum'),
            'templateName'  => $this->post('templateName'),
            'templateType'  => $this->post('templateType'),
            'voucherNo'     => $this->post('voucherNo'),
            'text'          => $this->post('text'),
        ];

        $annotation = [
            'recordDate'    => '日期',
            'voucherWordId' => '凭证字',
        ];
        $rules      = [
            'recordDate'    => 'required',
            'voucherWordId' => 'required',
        ];

        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where         = " id = '$id' ";
        $info          = query(self::table, $where);
        $voucherNumAdd = $this->voucherSetting();
        $month         = date('Y-m', strtotime($field['recordDate']));
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif ($info['id'] && query('period_end_setting', "coid = '".self::$coid."' and id = '{$info['sourceId']}'")['name'] == '结转本期损益') {
            $json['warn'] = '此凭证为系统生成，不能修改';
        } elseif ($info['id'] && $info['auditStid'] && $info['workFlow'] != '待审核') {
            //此凭证在结账期间内，则不可更改
            $json['warn'] = '此凭证已审核，不能修改';
        } elseif (static::is_null_array($mxIds)) {
            $json['warn'] = '请填写凭证内容';
        } elseif (count(array_filter($subjectIds)) < 2) {
            $json['warn'] = '保存凭证需至少两行分录';
        } elseif (empty(array_filter($subjectIds))) {
            $json['warn'] = '请选择科目';
        } elseif ($voucherNumAdd != '是' && (empty($field['voucherNo']) || preg_match(checkInteger, $field['voucherNo']) == 0)) {
            $json['warn'] = '请填写凭证号';
        } elseif (($voucherNumAdd == '否' || $source != '插入') && $info['id'] && self::total(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and isTemplate = '否' and voucherWordId = '$field[voucherWordId]' and voucherNo='$field[voucherNo]' and date_format(recordDate,'%Y-%m') = '$month' and id !='$id'")) > 0) {
            $json['warn'] = '已存在此凭证字号';
        } elseif (round(array_sum($jieMoneys), 2) != round(array_sum($daiMoneys), 2)) {
            $json['warn'] = '借贷金额不相等';
        } elseif (count(array_filter($subjectIds)) != count(array_filter($jieMoneys)) + count(array_filter($daiMoneys))) {
            $json['warn'] = '科目或金额未填写完成';
        } elseif (empty($info['id']) && $source == '红冲' && empty($sourceId)) {
            $json['warn'] = '未找到红冲对应的凭证';
        } else {
            $this->startTrans();
            $company = query('company', "coid = '" . self::$coid . "'");
            if ($company['isAudit']) {
                $field['workFlow'] = '待审核';
            } else {
                $field['workFlow']   = '已记账';
                $field['auditStid']  = $company['auditStid'];
                $field['recordStid'] = $company['managerId'];
            }

            if (!$info['id']) {
                if ($voucherNumAdd == '是' && $source != '插入') {
                    //自动补号
                    $field['voucherNo'] = self::voucherNo($field['voucherWordId'], $field['recordDate']);
                }
                $field['sourceId']  = $sourceId;
                $field              = array_merge($field, [
                    'id'         => $id,
                    'coid'       => self::$coid,
                    'isTemplate' => '否',
                    'stid'       => self::$stid,
                    'source'     => $source
                ]);
                /*$period_end_setting = query('period_end_setting', "id = '$sourceId'");
                if (in_array($period_end_setting['type'], ['结转损益（收入）', '结转损益（费用）'])) {
                    $field['source'] = '结转损益';
                }*/
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            $totalMoney = 0;
            $ids        = [];
            foreach ($mxIds as $k => $mxId) {
                $index  = $k + 1;
                $detail = query(self::table_mx, "id = '$mxId'");
                if ($subjectIds[$mxId]) {
                    $subject = query('subject', "id = '$subjectIds[$mxId]'");
                    $ids[]   = $mxId;
                    $bool    = $this->assistAccountJuage($subject, $index, $mxId, [
                        'khid'         => $khids,
                        'supplierId'   => $subjectIds,
                        'departmentId' => $departmentIds,
                        'projectId'    => $projectIds,
                        'staffId'      => $staffIds,
                        'materialId'   => $materialIds,
                        'cashId'       => $cashIds,
                        'subjectId'    => $subjectIds
                    ]);
                    if (empty($summarys[$mxId])) {
                        $json['warn'] = "请填写第【{$index}】行摘要";
                        break;
                    } elseif (empty($jieMoneys[$mxId]) && empty($daiMoneys[$mxId])) {
                        $json['warn'] = "请填写第【{$index}】行金额";
                        break;
                    } elseif ($bool !== true) {
                        $json['warn'] = $bool;
                        break;
                    }
                    $jieMoneys[$mxId] = $jieMoneys[$mxId] ?: 0;
                    $daiMoneys[$mxId] = $daiMoneys[$mxId] ?: 0;
                    if ($jieMoneys[$mxId] != 0) {
                        $direction = '借';
                    } else {
                        $direction = '贷';
                    }
                    if ($source == '红冲' || $info['source'] == '红冲') {
                        $jieMoneys[$mxId] = -$jieMoneys[$mxId];
                        $daiMoneys[$mxId] = -$daiMoneys[$mxId];
                    }
                    $voucherPrice = $voucherPrices[$mxId] ?: 0;
                    $voucherNum   = $voucherNums[$mxId] ?: 0;
                    $voucherRate  = $voucherRates[$mxId] ?: 0;
                    $collection   = [
                        'voucherPrice' => self::formatPrice($voucherPrice),
                        'voucherRate'  => $voucherRate,
                        'voucherMoney' => $voucherRate > 0 ? round($voucherPrice * $voucherNum / $voucherRate, 2) : 0,
                    ];
                    $totalMoney   += $direction == '借' ? self::yuanToCent($jieMoneys[$mxId]) : 0;
                    $material     = query('material', "id = '$materialIds[$mxId]'");
                    $mxField      = [
                        'summary'      => $summarys[$mxId],
                        'subjectId'    => $subjectIds[$mxId],
                        'subjectName'  => $subject['name'],
                        'subjectCode'  => $subject['code'],
                        'direction'    => $direction,
                        'money'        => $direction == '借' ? self::yuanToCent($jieMoneys[$mxId]) : self::yuanToCent($daiMoneys[$mxId]),
                        'subjectAttr'  => json_encode($collection, 320),
                        'khid'         => $khids[$mxId],
                        'supplierId'   => $supplierIds[$mxId],
                        'staffId'      => $staffIds[$mxId],
                        'projectId'    => $projectIds[$mxId],
                        'materialId'   => $materialIds[$mxId],
                        'cashId'       => $cashIds[$mxId],
                        'departmentId' => $departmentIds[$mxId],
                        'voucherNum'   => self::formatNum($voucherNum),
                        'currencyId'   => $currencyIds[$k] ?? '',
                        'unit'         => $material['unit'] ?: $subject['numAccountText'],
                        'rowList'      => $index
                    ];
                    $idCollection = array_filter([$mxField['khid'], $mxField['staffId'], $mxField['supplierId'], $mxField['projectId'], $mxField['materialId'], $mxField['departmentId'], $mxField['cashId']]);
                    asort($idCollection);
                    if (empty($detail['id'])) {
                        $mxField = array_merge($mxField, [
                            'id'           => $mxId,
                            'coid'         => self::$coid,
                            'orderId'      => $id,
                            'idCollection' => implode(',', $idCollection)
                        ]);
                        $warn    = static::insert(array(
                            'table' => self::table_mx,
                            'field' => $mxField,
                        ));
                    } else {
                        $mxField = array_merge($mxField, [
                            'idCollection' => implode(',', $idCollection)
                        ]);
                        $warn    = static::update(array(
                            'table' => self::table_mx,
                            'field' => $mxField,
                            'where' => "id = '$detail[id]'"
                        ));
                    }
                    if (!in_array($warn, ["新增成功", "更新成功"])) {
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }
            $warn = update(array('table' => self::table, 'field' => ['money' => $totalMoney], 'where' => "id = '$id'"));
            if ($warn != '更新成功') {
                $json['warn'] = $warn;
            }
            //附件
            $fileIdArr = $this->post('fileId');
            if (is_array($fileIdArr)) {
                $warn = update(array(
                    'table' => 'file',
                    'field' => ['targetId' => $id],
                    'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"
                ));
                if ($warn != '更新成功') {
                    $json['warn'] = $warn;
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                delete(array('table' => self::table_mx, "where" => "id not in ('" . implode("','", $ids) . "') and orderId = '$id'"));
                if ($source == '插入' && $json['warn'] == '新增成功') {
                    //更新凭证号
                    $all = find(array(
                        'table' => self::table,
                        'where' => "coid = '" . self::$coid . "' and recordDate >= '$field[recordDate]'  and voucherWordId = '$field[voucherWordId]' and id !='$id' order by recordDate asc,voucherNo asc"
                    ));
                    foreach ($all['array'] as $array) {
                        update(array(
                            'table' => self::table,
                            'field' => array(
                                'voucherNo' => $array['voucherNo'] + 1
                            ),
                            'where' => "id = '$array[id]'"
                        ));
                    }
                }
                $voucherWord = query('voucher_word', "id = '$field[voucherWordId]'");
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】,凭证号：' . $voucherWord['word'] . '-' . $field['voucherNo'];
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = match ($href) {
                    'new' => root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home",
                    'copy' => root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home&method=template&id=" . $id,
                    default => root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home&id=" . $id
                };
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }


    public function salary($param)
    {
        $col_list = 0;
        //工资凭证
        $dataTr         = '';
        $month          = $param['month'];
        $salary_setting = query('salary_setting', "id = '" . $param['settingId'] . "'");
        $jieTotalMoney  = $daiTotalMoney = 0;
        $all            = find(array('table' => 'salary_setting_detail', 'where' => "orderId = '$salary_setting[id]' order by list asc"));
        foreach ($all['array'] as $array) {
            $mxId    = suiji();
            $subject = query('subject', "id = '$array[subjectId]'");
            if ($array['direction'] == '借') {
                if (in_array($subject['code'], ['5602001', '5601001'])) {
                    //管理人员和销售人员职工薪酬
                    $jieMoney = $this->calculateMoney($array['subjectId'], $array['rule'], $month);
                } else {
                    $jieMoney = $this->calculateMoney('', $array['rule'], $month);
                }
                $daiMoney = 0;
            } else {
                if (in_array($subject['code'], ['5602001', '5601001'])) {
                    //管理人员和销售人员职工薪酬
                    $daiMoney = $this->calculateMoney($array['subjectId'], $array['rule'], $month);
                } else {
                    $daiMoney = $this->calculateMoney('', $array['rule'], $month);
                }
                $jieMoney = 0;
            }
            $jieMoneyText = self::yuanToCent($jieMoney) ?: '';
            $jieMoneyText = self::splitNumber($jieMoneyText);

            $daiMoneyText   = self::yuanToCent($daiMoney) ?: '';
            $daiMoneyText   = self::splitNumber($daiMoneyText);
            $numAccountHide = 'hide';
            if ($subject['numAccount'] == '是') {
                $numAccountHide = '';
            }
            $assistName      = ' ';
            $currencyAccount = 'hide';
            if ($subject['currencyAccount'] == '是') {
                $currencyAccount = '';
            }
            $jieTotalMoney   += $jieMoney;
            $daiTotalMoney   += $daiMoney;
            $subject['name'] = subjectClass::getName($subject['id']);
            $col_list++;
            $dataTr .= <<<eof
<div class="container-body-row">
 <div class="cell center setting-col"><span>$col_list</span></div>
 <div class="cell oprate-col">
    <img alt="复制此行" title="复制此行" class="copy_v_btn" src="{$this->copyIcon}">
    <img alt="添加一行" title="添加一行" class="add_v_btn" src="{$this->addIco}">
    <img alt="删除此行" title="删除此行" class="del_v_btn" src="{$this->delIco}"> 
 </div>
 <div class="cell summary-col">
    <input name="mxId[]" data-id="$mxId" type="hidden" value="$mxId">
    <div class="summary">{$salary_setting['name']}</div><textarea class="summary-input hide hide-input" name="summary[$mxId]" type="text" maxlength="220">{$salary_setting['name']}</textarea>
 </div>
 <div class="cell subject-col">
    <div class="subject-input-parent"><textarea class="subject-input hide hide-input" type="text" maxlength="220">{$subject['code']} {$subject['name']}$assistName</textarea></div>
    <div class="subject-content subject-text">
        <div class="subject-name">{$subject['code']} {$subject['name']}$assistName</div>
        <div class="balance hide">
            余额：<span class="balance-money" onclick="accountMx(event,this)">0</span>
        </div>
        <input type="hidden" name="subjectId[$mxId]" value="$subject[id]">
        <input type="hidden" name="khid[$mxId]" value="">
        <input type="hidden" name="supplierId[$mxId]" value="">
        <input type="hidden" name="staffId[$mxId]" value="">
        <input type="hidden" name="projectId[$mxId]" value="">
        <input type="hidden" name="materialId[$mxId]" value="">
        <input type="hidden" name="cashId[$mxId]" value="">
        <input type="hidden" name="departmentId[$mxId]">
    </div>
 </div>
 <div class="cell num-col">
        <div class="num-name $numAccountHide">
            <div><span class="voucher-num-btn">数量：</span><span class="voucher-num-text">0</span><input name="voucherNum[$mxId]" type="hidden" value=""></div>
            <div><span class="voucher-price-btn">单价：</span><span class="voucher-price-text">0</span><input  name="voucherPrice[$mxId]" type="hidden" value=""></div>
        </div>
        <div class="currency-name $currencyAccount">
            <div><span class="voucher-money-btn"></span><span class="voucher-money-text">0</span><input name="voucherMoney[$mxId]" type="hidden" value=""><input name="currencyId[$mxId]" type="hidden" value=""></div>
            <div><span class="voucher-rate-btn">汇率：</span><span class="voucher-rate-text">0</span><input class="hide voucher-rate-input"  name="voucherRate[$mxId]" type="hidden" value=""></div>
        </div>
 </div>
  <div class="cell jie-col">
        <div class="show_text show_money jie">
           <div class="jie-text format-line-box">
                $jieMoneyText
           </div>
        </div><input class="money-input hide hide-input jie-input" name="jieMoney[$mxId]" value="$jieMoney">
  </div>
  <div class="cell dai-col">
    <div class="show_text show_money dai">
        <div class="dai-text format-line-box">
            $daiMoneyText
        </div>
    </div><input class="money-input hide hide-input dai-input" name="daiMoney[$mxId]" value="$daiMoney">
  </div>    
</div>
eof;
        }
        return ['html' => $dataTr, 'jieTotal' => $jieTotalMoney, 'daiTotal' => $daiTotalMoney];
    }


    /**
     * 期末结转凭证
     */
    public function endPeriod($param)
    {
        $dataTr           = '';
        $sourceId         = $param['sourceId'];
        $terminalTransfer = new terminalTransferClass();
        $result           = $terminalTransfer->endPeriodVoucher($param); //结转数据
        $accountDetail    = new accountDetailsClass();
        $month            = $param['month'];
        $jieTotalMoney    = $daiTotalMoney = 0;
        $col_list         = 0;
        foreach ($result as $res) {
            $col_list++;
            $mxId           = self::getId();
            $redClass       = '';
            $voucherId      = $res['voucherId'] ?? '';
            $array          = query("voucher_detail", " id = '$voucherId' ");
            $balanceHide    = $array['id'] ? '' : 'hide';//控制余额是否显示
            $subjectAttr    = json_decode($array['subjectAttr'], true);
            $subjectId      = $array['subjectId'] ?: $res['subjectId'];
            $subject        = query('subject', "id = '$subjectId'");
            $jieMoney       = $res['jieMoney'];
            $daiMoney       = $res['daiMoney'];
            $jieMoneyText   = self::yuanToCent($jieMoney) ?: '';
            $daiMoneyText   = self::yuanToCent($daiMoney) ?: '';
            $currency       = query('currency', "id = '$array[currencyId]'");
            $numAccountHide = 'hide';
            if ($subject['numAccount'] == '是') {
                $numAccountHide = '';
            }
            $assistName = '';
            if ($subject['assistAccount'] == '是') {
                $assistName = '';
                if (!empty($array['khid'])) {
                    $kehu       = query('kehu', "khid = '$array[khid]'");
                    $assistName .= '_' . $kehu['orderNo'] . $kehu['companyName'];
                }
                if (!empty($array['supplierId'])) {
                    $supplier   = query('supplier', "id = '$array[supplierId]'");
                    $assistName .= '_' . $supplier['code'] . $supplier['name'];
                }
                if (!empty($array['staffId'])) {
                    $staff      = query('staff', "stid = '$array[staffId]'");
                    $assistName .= '_' . $staff['orderNo'] . $staff['name'];
                }
                if (!empty($array['departmentId'])) {
                    $department = query('department', "id = '$array[departmentId]'");
                    $assistName .= '_' . $department['name'];
                }
                if (!empty($array['materialId'])) {
                    $assistName .= '_' . materialClass::getName($array['materialId'], '');
                }
                if (!empty($array['projectId'])) {
                    $project    = query('project', "id = '$array[projectId]'");
                    $assistName .= '_' . $project['orderNo'] . $project['name'];
                }
                if (!empty($array['cashId'])) {
                    $cash       = query('cash', "id = '$array[cashId]'");
                    $assistName .= '_' . $cash['code'] . $cash['name'];
                }
            }
            $assistName      = ' ' . ltrim($assistName, '_');
            $currencyAccount = 'hide';
            if ($subject['currencyAccount'] == '是') {
                $currencyAccount = '';
            }
            $jieTotalMoney               += $jieMoney;
            $daiTotalMoney               += $daiMoney;
            $balance                     = $accountDetail->balanceCul($this->date, $subject['id'], '累计', assetIds: (array)explode(',', $array['idCollection']));
            $balanceMoney                = $balance['balance'];
            $subject['name']             = subjectClass::getName($subject['id']);
            $array['voucherNum']         = self::formatZero($array['voucherNum']);
            $subjectAttr['voucherPrice'] = !empty($subjectAttr['voucherPrice'] ?? '') ? self::formatZero($subjectAttr['voucherPrice'], 2) : '';
            $subjectAttr['voucherMoney'] = !empty($subjectAttr['voucherMoney'] ?? '') ? self::formatZero($subjectAttr['voucherMoney'], 2) : '';
            $jieMoneyText                = self::splitNumber($jieMoneyText);
            $daiMoneyText                = self::splitNumber($daiMoneyText);
            //  <div class="assist-name $assistAccount">{$assistName}</div>
            $dataTr .= <<<eof
<div class="container-body-row">
    <div class="cell center setting-col"><span>$col_list</span></div>
    <div class="cell oprate-col">
            <img alt="复制此行" title="复制此行" class="copy_v_btn" src="{$this->copyIcon}">
            <img alt="添加一行" title="添加一行" class="add_v_btn" src="{$this->addIco}">
            <img alt="删除此行" title="删除此行" class="del_v_btn" src="{$this->delIco}"> 
    </div>
    <div class="cell summary-col">
        <input name="mxId[]" data-id="$mxId" type="hidden" value="$mxId">
        <div class="summary">{$res['summary']}</div>
        <textarea class="summary-input hide hide-input" name="summary[$mxId]" type="text" maxlength="220">{$res['summary']}</textarea>
    </div>
    <div class="cell subject-col">
          <div class="subject-input-parent">
                <textarea class="subject-input hide hide-input" type="text" maxlength="220">{$subject['code']} {$subject['name']}$assistName</textarea>
          </div>
          <div class="subject-content subject-text" data-asset="{$array['idCollection']}">
                <div class="subject-name">{$array['subjectCode']} {$subject['name']}$assistName</div>
                 <div class="balance $balanceHide">
                    余额：<span class="balance-money" onclick="accountMx(event,this)">$balanceMoney</span>
                </div>
                <input type="hidden" name="subjectId[$mxId]" value="$subject[id]">
                <input type="hidden" name="khid[$mxId]" value="$array[khid]">
                <input type="hidden" name="supplierId[$mxId]" value="$array[supplierId]">
                <input type="hidden" name="staffId[$mxId]" value="$array[staffId]">
                <input type="hidden" name="projectId[$mxId]" value="$array[projectId]">
                <input type="hidden" name="materialId[$mxId]" value="$array[materialId]">
                <input type="hidden" name="cashId[$mxId]" value="$array[cashId]">
                <input type="hidden" name="departmentId[$mxId]" value="$array[departmentId]">
          </div>
    </div>
    <div class="cell num-col">
          <div class="num-name $numAccountHide">
              <div><span class="voucher-num-btn">数量：</span><span class="voucher-num-text">{$array['voucherNum']}</span><input name="voucherNum[$mxId]" type="hidden" value="{$array['voucherNum']}"></div>
              <div><span class="voucher-price-btn">单价：</span><span class="voucher-price-text">{$subjectAttr['voucherPrice']}</span><input  name="voucherPrice[$mxId]" type="hidden" value="{$subjectAttr['voucherPrice']}"></div>
          </div>
          <div class="currency-name $currencyAccount">
              <div><span class="voucher-money-btn">{$currency['code']}：</span><span class="voucher-money-text">{$subjectAttr['voucherMoney']}</span><input name="voucherMoney[$mxId]" type="hidden" value="{$subjectAttr['voucherMoney']}"><input name="currencyId[$mxId]" type="hidden" value="{$array['currencyId']}"></div>
              <div><span class="voucher-rate-btn">汇率：</span><span class="voucher-rate-text">{$currency['rate']}</span><input class="hide voucher-rate-input"  name="voucherRate[$mxId]" type="hidden" value="{$currency['rate']}"></div>
          </div>
    </div>
    <div class="cell jie-col">
        <div class="show_text show_money jie">
            <div class="jie-text $redClass format-line-box">
                $jieMoneyText
            </div>
        </div>
        <input class="money-input hide hide-input jie-input" name="jieMoney[$mxId]"   value="$jieMoney">
    </div>
   <div class="cell dai-col">
        <div class="show_text show_money dai">
            <div class="dai-text $redClass format-line-box">$daiMoneyText</div>
        </div>
        <input class="money-input hide hide-input dai-input" name="daiMoney[$mxId]"   value="$daiMoney">
   </div></div>
eof;
        }
        $jieTotal = $jieTotalMoney;
        $daiTotal = $daiTotalMoney;
        return ['html' => $dataTr, 'jieTotal' => $jieTotal, 'daiTotal' => $daiTotal, 'col_list' => $col_list];
    }

    /**
     * 结转损益
     * 将损益类的科目余额全部转为0
     */
    public function carryOver($id, $param): array
    {
        $rule = companyClass::returnRule(1);
        if ($rule == 'enterpriseRule') {
            $subjectCode = '4103';
        } else {
            $subjectCode = '3103';
        }
        $col_list      = 0;
        $dataTr        = '';
        $transfer      = new terminalTransferClass();
        $multObj       = new multiColumnAccountClass();
        $month         = $param['month'];
        $jieTotalMoney = $daiTotalMoney = 0;
        $all           = find(array('table' => 'period_end_setting_detail', 'where' => "orderId = '$id' order by list asc"));
        foreach ($all['array'] as $array) {
            $columns = [];
            $multObj->loopSubjectIds($array['subjectId'], $columns);
            foreach ($columns as $subjectId) {
                $col_list++;
                $subject = query('subject', "id = '$subjectId'");
                $balance = $transfer->balanceOnlyMoney($month, $subject['id']);
                if ($subject['direction'] == '借') {
                    $jieMoney = 0;
                    $daiMoney = $balance;
                } else {
                    $daiMoney = 0;
                    $jieMoney = $balance;
                }

                if (abs($balance) > 0 && $subject['code'] != $subjectCode) {
                    $mxId           = suiji();
                    $jieMoneyText   = self::splitNumber(self::yuanToCent($jieMoney));
                    $daiMoneyText   = self::splitNumber(self::yuanToCent($daiMoney));
                    $numAccountHide = 'hide';
                    if ($subject['numAccount'] == '是') {
                        $numAccountHide = '';
                    }
                    $assistName      = ' ';
                    $currencyAccount = 'hide';
                    if ($subject['currencyAccount'] == '是') {
                        $currencyAccount = '';
                    }
                    $jieTotalMoney   += $jieMoney;
                    $daiTotalMoney   += $daiMoney;
                    $summary         = date('m月', strtotime($month . '-01')) . '结转损益';
                    $subject['name'] = subjectClass::getName($subject['id']);
                    $dataTr          .= <<<eof
<div class="container-body-row">
 <div class="cell center setting-col"><span>$col_list</span></div>
 <div class="cell oprate-col">
    <img alt="复制此行" title="复制此行" class="copy_v_btn" src="{$this->copyIcon}">
    <img alt="添加一行" title="添加一行" class="add_v_btn" src="{$this->addIco}">
    <img alt="删除此行" title="删除此行" class="del_v_btn" src="{$this->delIco}"> 
 </div>
 <div class="cell summary-col">
    <input name="mxId[]" data-id="$mxId" type="hidden" value="$mxId">
    <div class="summary">$summary</div><textarea class="summary-input hide hide-input" name="summary[$mxId]" type="text" maxlength="220">$summary</textarea>
 </div>
 <div class="cell subject-col">
    <div class="subject-input-parent"><textarea class="subject-input hide hide-input" type="text" maxlength="220">{$subject['code']} {$subject['name']}$assistName</textarea></div>
    <div class="subject-content subject-text">
        <div class="subject-name">{$subject['code']} {$subject['name']}$assistName</div>
        <div class="balance hide">
            余额：<span class="balance-money" onclick="accountMx(event,this)">0</span>
        </div>
        <input type="hidden" name="subjectId[$mxId]" value="$subject[id]">
        <input type="hidden" name="khid[$mxId]" value="">
        <input type="hidden" name="supplierId[$mxId]" value="">
        <input type="hidden" name="staffId[$mxId]" value="">
        <input type="hidden" name="projectId[$mxId]" value="">
        <input type="hidden" name="materialId[$mxId]" value="">
        <input type="hidden" name="cashId[$mxId]" value="">
        <input type="hidden" name="departmentId[$mxId]">
    </div>
 </div>
 <div class="cell num-col">
        <div class="num-name $numAccountHide">
            <div><span class="voucher-num-btn">数量：</span><span class="voucher-num-text">0</span><input name="voucherNum[$mxId]" type="hidden" value=""></div>
            <div><span class="voucher-price-btn">单价：</span><span class="voucher-price-text">0</span><input  name="voucherPrice[$mxId]" type="hidden" value=""></div>
        </div>
        <div class="currency-name $currencyAccount">
            <div><span class="voucher-money-btn"></span><span class="voucher-money-text">0</span><input name="voucherMoney[$mxId]" type="hidden" value=""><input name="currencyId[$mxId]" type="hidden" value=""></div>
            <div><span class="voucher-rate-btn">汇率：</span><span class="voucher-rate-text">0</span><input class="hide voucher-rate-input"  name="voucherRate[$mxId]" type="hidden" value=""></div>
        </div>
 </div>
  <div class="cell jie-col">
        <div class="show_text show_money jie">
         <div class="jie-text format-line-box">
                $jieMoneyText
            </div>
        </div><input class="money-input hide hide-input jie-input" name="jieMoney[$mxId]" value="$jieMoney">
  </div>
  <div class="cell dai-col">
    <div class="show_text show_money dai">
    <div class="dai-text format-line-box">$daiMoneyText</div>
    </div><input class="money-input hide hide-input dai-input" name="daiMoney[$mxId]" value="$daiMoney">
  </div>    
</div>
eof;
                }
            }
        }

        if (!empty($dataTr)) {
            $subject = query('subject', "code = '$subjectCode' and coid = '" . self::$coid . "'");//本年利润科目
            $mxId    = suiji();
            if ($jieTotalMoney > $daiTotalMoney) {
                $jieMoney = 0;
                $daiMoney = $jieTotalMoney - $daiTotalMoney;
            } else {
                $daiMoney = 0;
                $jieMoney = $daiTotalMoney - $jieTotalMoney;
            }
            $jieMoneyText   = self::splitNumber(self::yuanToCent($jieMoney));
            $daiMoneyText   = self::splitNumber(self::yuanToCent($daiMoney));
            $numAccountHide = 'hide';
            if ($subject['numAccount'] == '是') {
                $numAccountHide = '';
            }
            $assistName      = ' ';
            $currencyAccount = 'hide';
            if ($subject['currencyAccount'] == '是') {
                $currencyAccount = '';
            }

            $jieTotalMoney   += $jieMoney;
            $daiTotalMoney   += $daiMoney;
            $summary         = date('m月', strtotime($month . '-01')) . '结转损益';
            $subject['name'] = subjectClass::getName($subject['id']);
            $col_list++;
            $dataTr = <<<eof
<div class="container-body-row">
 <div class="cell center setting-col"><span>$col_list</span></div>
 <div class="cell oprate-col">
    <img alt="复制此行" title="复制此行" class="copy_v_btn" src="{$this->copyIcon}">
    <img alt="添加一行" title="添加一行" class="add_v_btn" src="{$this->addIco}">
    <img alt="删除此行" title="删除此行" class="del_v_btn" src="{$this->delIco}"> 
 </div>
 <div class="cell summary-col">
    <input name="mxId[]" data-id="$mxId" type="hidden" value="$mxId">
    <div class="summary">$summary</div><textarea class="summary-input hide hide-input" name="summary[$mxId]" type="text" maxlength="220">$summary</textarea>
 </div>
 <div class="cell subject-col">
    <div class="subject-input-parent"><textarea class="subject-input hide hide-input" type="text" maxlength="220">{$subject['code']} {$subject['name']}$assistName</textarea></div>
    <div class="subject-content subject-text">
        <div class="subject-name">{$subject['code']} {$subject['name']}$assistName</div>
        <div class="balance hide">
            余额：<span class="balance-money" onclick="accountMx(event,this)">0</span>
        </div>
        <input type="hidden" name="subjectId[$mxId]" value="$subject[id]">
        <input type="hidden" name="khid[$mxId]" value="">
        <input type="hidden" name="supplierId[$mxId]" value="">
        <input type="hidden" name="staffId[$mxId]" value="">
        <input type="hidden" name="projectId[$mxId]" value="">
        <input type="hidden" name="materialId[$mxId]" value="">
        <input type="hidden" name="cashId[$mxId]" value="">
        <input type="hidden" name="departmentId[$mxId]">
    </div>
 </div>
 <div class="cell num-col">
        <div class="num-name $numAccountHide">
            <div><span class="voucher-num-btn">数量：</span><span class="voucher-num-text">0</span><input name="voucherNum[$mxId]" type="hidden" value=""></div>
            <div><span class="voucher-price-btn">单价：</span><span class="voucher-price-text">0</span><input  name="voucherPrice[$mxId]" type="hidden" value=""></div>
        </div>
        <div class="currency-name $currencyAccount">
            <div><span class="voucher-money-btn"></span><span class="voucher-money-text">0</span><input name="voucherMoney[$mxId]" type="hidden" value=""><input name="currencyId[$mxId]" type="hidden" value=""></div>
            <div><span class="voucher-rate-btn">汇率：</span><span class="voucher-rate-text">0</span><input class="hide voucher-rate-input"  name="voucherRate[$mxId]" type="hidden" value=""></div>
        </div>
 </div>
  <div class="cell jie-col">
        <div class="show_text show_money jie">
         <div class="jie-text format-line-box">
                $jieMoneyText
            </div>
        </div><input class="money-input hide hide-input jie-input" name="jieMoney[$mxId]" value="$jieMoney">
  </div>
  <div class="cell dai-col">
    <div class="show_text show_money dai">
        <div class="dai-text format-line-box">$daiMoneyText</div>
    </div><input class="money-input hide hide-input dai-input" name="daiMoney[$mxId]" value="$daiMoney">
  </div>    
</div>
 $dataTr
eof;
        }

        return ['html' => $dataTr, 'jieTotal' => round($jieTotalMoney, 2), 'daiTotal' => round($daiTotalMoney, 2)];
    }

    /**
     * Desc : 记账凭证
     * User : you name
     * Date : 2024-06-11 13:53
     * @param $param
     * @return string
     */
    public function voucherHtml($param): string
    {
        $col_list      = 0;//行号
        $shortcutImg   = $this->shortcutImg . '?v=' . version;
        $printIco      = $this->printIcon . '?v=' . version;
        $dataTr        = '';//凭证行内容
        $jieTotalMoney = $daiTotalMoney = 0;//借方和贷方金额总计
        $helpUrlArr    = para('voucherHelpUrl', ';');
        $helpUrl       = match (companyClass::returnRule(1)) {
            'enterpriseRule' => $helpUrlArr[1] ?? '',//2007企业会计准则
            'smallEnterpriseRule' => $helpUrlArr[0] ?? '',//小企业会计准则
        };
        //为template时表示使用模板创建数据，为salary标识从工资创建凭证,为redChong:红冲 insert:插入
        $method      = $param['method'];
        $id          = $param['id'] ?: suiji();
        $info        = query(self::table, "id = '$id'");
        $voucherWord = query('voucher_word', "id = '$info[voucherWordId]'");
        $redClass    = '';//红冲时标红
        $source      = $method ? $this->typeOption[$method] : '正常';//来源类型
        $sourceId    = '';//来源ID,红冲时需要知道是哪张凭证的红冲
        $fromInfo    = $info;
        if ($source == '红冲' || $source == '复制') {
            $sourceId          = $info['id'];
            $id                = suiji();
            $info['voucherNo'] = '';
        }
        if ($info['source'] == '红冲' || $source == '红冲') {
            $redClass           = 'red-text';
            $info['recordDate'] = $this->date;
        }
        $lastVoucher = query(self::table, "coid = '" . self::$coid . "' order by time desc ");
        $info['recordDate'] = $info['recordDate'] ?: $this->date;
        $isEnd = false;//是否系统结转损益凭证
        $isSys = false; //是否系统期末结转模板
        if ($info['id'] && $info['sourceId']) {
            $period_end    = query('period_end_setting', "coid = '".self::$coid."' and id = '{$info['sourceId']}'");
            if($period_end['name'] == '结转本期损益') {  //结转损益凭证系统生成不可修改
                $isEnd = true;
            }
            if($period_end['isDel'] == 0) {  //系统期末结转模板
                $isSys = true;
            }
        }
        /*********生成工资凭证********/
        if ($method == 'salary') {
            $month                 = $param['month'];
            $salary_setting        = query('salary_setting', "id = '" . $param['settingId'] . "'");
            $info['voucherWordId'] = $salary_setting['voucherWordId'];
            $info['recordDate']    = $month . '-' . date('t', strtotime($month . '-01'));
            $result                = $this->salary($param);
            $dataTr                = $result['html'];
            $jieTotalMoney         = $result['jieTotal'];
            $daiTotalMoney         = $result['daiTotal'];
        } elseif ($method == 'endPeriod') {
            /******期末结转********************/
            $sourceId              = $param['sourceId'];
            $month                 = $param['month'];
            $period_end_setting    = query('period_end_setting', "id = '$sourceId'");
            $isSys = true;
            $info['voucherWordId'] = $period_end_setting['voucherWordId'];
            $info['recordDate']    = $month . '-' . date('t', strtotime($month . '-01'));
            $result                = $this->endPeriod($param);
            $dataTr                = $result['html'];
            $jieTotalMoney         = $result['jieTotal'];
            $daiTotalMoney         = $result['daiTotal'];
            $col_list              = $result['col_list'];
        }

        $defaultVoucherWord       = query('voucher_word', "coid = '" . self::$coid . "' and isDefault = '是'");
        $defaultVoucherWord['id'] = $lastVoucher['id'] ? $lastVoucher['voucherWordId'] : $defaultVoucherWord['id'];
        $fixDate                  = $this->voucherSetting('fixDate');
        if ($fixDate == '是' && empty($info['id'])) {
            $info['recordDate'] = $this->voucherSetting('fixDateValue');
        }
        //更多按钮
        $printButton = '';
        if ($info['id']) {
            $printButton = "<img alt='打印凭证' title='打印凭证' src='" . $printIco . "' onclick=\"window.open(root+'control/adIndex.html?cla=voucherEdit&fun=printPage&id={$info['id']}')\" />";
        }
        $disabled = $isEnd ? 'disabled' : '';//禁用控件
        $readonly = $isSys ? 'readonly' : '';//只读
        $aveAndAdd = "<span class=\"spanButton li-btn-blue-bg marginl0\" onclick=\"subForm('voucherForm',root+'control/adIndex.html?cla=voucherEdit&fun=editEdit&href=new')\">保存并新增</span>";
        if($isSys){
            $aveAndAdd = "";
        }
        $saveBtn  = $isEnd ? '' : <<<eof
$aveAndAdd
<span class="spanButton" onclick="subForm('voucherForm',root+'control/adIndex.html?cla=voucherEdit&fun=editEdit&href=save')">保存</span>
eof;

        $wordSelect = "<select id='voucherWordId' name='voucherWordId' onchange='changeVoucherWordId(this)' $disabled  style='width: 80px;height: 25px'>" . idSelect(array('type' => 'option', 'sqlForm' => "voucher_word where coid = '" . self::$coid . "' order by field(isDefault,'是','否'),time asc", 'sqlId' => 'id', 'sqlField' => 'word', 'value' => $info['voucherWordId'] ?: $defaultVoucherWord['id'])) . "</select>";

        $voucherNo = $info['voucherNo'] ?: self::voucherNo($defaultVoucherWord['id'], $info['recordDate']);
        if ($info['isTemplate'] == '是') {
            $voucherNo = self::voucherNo($info['voucherWordId'] ?: $defaultVoucherWord['id'], $this->date);
        }
        $recordDate = $disabled || $readonly ?
            text(array('name' => 'recordDate', 'class' => 'height23', 'other' => $readonly, 'value' => $info['recordDate'])):
            text(array('name' => 'recordDate', 'class' => 'height23', 'laydate' => ['min' => "'" . accountDetailsClass::getMinDate() . "'", "done" => "function(e){ $('[name=recordDate]').val(e);changeVoucherWordId()}"], 'value' => $info['recordDate']));

        //判断是否有多张凭证
        if(!$isSys) {
            if ($this->isPre($info['recordDate'], $voucherNo, $info['voucherWordId'] ?: $defaultVoucherWord['id'])) {
                $left      = $this->leftIco . '?v=' . version;
                $leftTitle = '上一张';
            } else {
                $left      = $this->leftIcoGray . '?v=' . version;
                $leftTitle = '没有上一张凭证了';
            }

            $directionButton = "<img alt='$leftTitle' src='$left'  id='pre-button' class='pre-button' data-id='{$info['id']}' data-type='pre' title='$leftTitle'>";
            //判断是否有下一张凭证
            if ($this->isNext($info['recordDate'], $voucherNo, $info['voucherWordId'] ?: $defaultVoucherWord['id'])) {
                $right      = $this->rightIcon . '?v=' . version;
                $rightTitle = '下一张凭证';
            } else {
                $right      = $this->rightIconGray . '?v=' . version;
                $rightTitle = '没有下一张凭证了';
            }
            $directionButton .= "<img alt='$rightTitle' src='$right'  id='next-button' class='next-button' data-id='{$info['id']}' data-type='next' title='$rightTitle'>";
            $staffName       = self::total(['table' => self::table, 'where' => "id = '$id'"]) ? self::findStaff($info['stid']) : $this->control['name'];
        }else{
            $directionButton = '';
            $staffName = '';
        }

        //快捷键按钮
        $this->keyboardIcon = $this->keyboardIcon . '?v=' . version;
        $shortCutButton     = <<<eof
 <div class="shortcut-key"  id="shortKey">
    <img alt="点击查看快捷键" title="点击查看快捷键" src="{$this->keyboardIcon}"/>
   
    <div class="shortcut-key-content">
     <div class="arrow"></div>
        <div><p>键盘常用操作</p></div>
        <div class="shortcut-img"><img alt=""  src="$shortcutImg" /></div>
        <div class="shortcut-table">
            <table class="tableMany">
            <thead><tr><td>凭证</td><td>快捷键</td></tr></thead>
            <tbody>
                <tr><td>保存并新增</td><td>F12</td></tr>
                <tr><td>保存</td><td>Ctrl+S</td></tr>
                <tr><td>新增</td><td>Alt+N</td></tr>
                <tr><td>录入第二条分录</td><td>Enter</td></tr>
                <tr><td>自动平衡借贷方金额</td><td>=</td></tr>
            </tbody>
            </table>
        </div>
    </div>
    </div>
eof;
        //使用模板按钮
        $useTemplateButton = "<img alt='使用模板' title='使用模板' src='" . $this->useTemplateIcon . '?v=' . version . "' onclick=\"layer('voucherEdit', 'template', {})\">";
        if ($info['id'] && !in_array($method, ['insert', 'salary', 'endPeriod'])) {
            $all = find(array('table' => self::table_mx, 'where' => "orderId = '$info[id]' order by rowList,list asc"));
            foreach ($all['array'] as $array) {
                $col_list++;
                $mxId        = $array['id'];
                $balanceHide = '';//控制余额是否显示
                if ($method == 'template') {
                    //模板
                    $mxId        = suiji();
                    $balanceHide = 'hide';
                } elseif ($method == 'redChong') {
                    //红冲
                    $mxId             = suiji();
                    $array['summary'] = '冲销' . date('Ym', strtotime($info['recordDate'])) . $voucherWord['word'] . '-' . $fromInfo['voucherNo'] . '_' . $array['summary'];
                    $balanceHide      = 'hide';
                }
                if ($info['source'] == '红冲' || $method == 'redChong') {
                    //红冲
                    $array['money'] = abs($array['money']);
                    $balanceHide    = 'hide';
                }
                $subjectAttr    = json_decode($array['subjectAttr'], true);
                $subject        = query('subject', "id = '$array[subjectId]'");
                $jieMoney       = $array['direction'] == '借' ? self::centToYuan($array['money']) : 0;
                $daiMoney       = $array['direction'] == '贷' ? self::centToYuan($array['money']) : 0;
                $jieMoneyText   = self::yuanToCent($jieMoney) ?: '';
                $daiMoneyText   = self::yuanToCent($daiMoney) ?: '';
                $currency       = query('currency', "id = '$array[currencyId]'");
                $numAccountHide = 'hide';
                if ($subject['numAccount'] == '是') {
                    $numAccountHide = '';
                }
                $assistName = '';
                if ($subject['assistAccount'] == '是') {
                    $assistName = '';
                    if (!empty($array['khid'])) {
                        $kehu       = query('kehu', "khid = '$array[khid]'");
                        $assistName .= '_' . $kehu['orderNo'] . $kehu['companyName'];
                    }
                    if (!empty($array['supplierId'])) {
                        $supplier   = query('supplier', "id = '$array[supplierId]'");
                        $assistName .= '_' . $supplier['code'] . $supplier['name'];
                    }
                    if (!empty($array['staffId'])) {
                        $staff      = query('staff', "stid = '$array[staffId]'");
                        $assistName .= '_' . $staff['orderNo'] . $staff['name'];
                    }
                    if (!empty($array['departmentId'])) {
                        $department = query('department', "id = '$array[departmentId]'");
                        $assistName .= '_' . $department['name'];
                    }
                    if (!empty($array['materialId'])) {
                        $assistName .= '_' . materialClass::getName($array['materialId'], '');
                    }
                    if (!empty($array['projectId'])) {
                        $project    = query('project', "id = '$array[projectId]'");
                        $assistName .= '_' . $project['orderNo'] . $project['name'];
                    }
                    if (!empty($array['cashId'])) {
                        $cash       = query('cash', "id = '$array[cashId]'");
                        $assistName .= '_' . $cash['code'] . $cash['name'];
                    }
                }
                $assistName      = ' ' . ltrim($assistName, '_');
                $currencyAccount = 'hide';
                if ($subject['currencyAccount'] == '是') {
                    $currencyAccount = '';
                }
                $jieTotalMoney               += $jieMoney;
                $daiTotalMoney               += $daiMoney;
                $accountDetail               = new accountDetailsClass();
                $balance                     = $accountDetail->balanceCul($info['recordDate'], $subject['id'], '累计', assetIds: (array)explode(',', $array['idCollection']));
                $balanceMoney                = $balance['balance'];
                $subject['name']             = subjectClass::getName($subject['id']);
                $array['voucherNum']         = self::formatZero($array['voucherNum']);
                $subjectAttr['voucherPrice'] = self::formatZero($subjectAttr['voucherPrice'], 2) ?? '';
                $jieMoneyText                = self::splitNumber($jieMoneyText);
                $daiMoneyText                = self::splitNumber($daiMoneyText);
                //  <div class="assist-name $assistAccount">{$assistName}</div>
                $dataTr .= <<<eof
<div class="container-body-row">
    <div class="cell center setting-col"><span>$col_list</span></div>
    <div class="cell oprate-col">
            <img alt="复制此行" title="复制此行" class="copy_v_btn" src="{$this->copyIcon}">
            <img alt="添加一行" title="添加一行" class="add_v_btn" src="{$this->addIco}">
            <img alt="删除此行" title="删除此行" class="del_v_btn" src="{$this->delIco}"> 
    </div>
    <div class="cell summary-col">
        <input name="mxId[]" data-id="$mxId" type="hidden" value="$mxId">
        <div class="summary">{$array['summary']}</div>
        <textarea class="summary-input hide hide-input" name="summary[$mxId]" type="text" maxlength="220">{$array['summary']}</textarea>
    </div>
    <div class="cell subject-col">
          <div class="subject-input-parent">
                <textarea class="subject-input hide hide-input" type="text" maxlength="220">{$subject['code']} {$subject['name']}$assistName</textarea>
          </div>
          <div class="subject-content subject-text" data-asset="{$array['idCollection']}">
                <div class="subject-name">{$array['subjectCode']} {$subject['name']}$assistName</div>
                 <div class="balance $balanceHide">
                    余额：<span class="balance-money" onclick="accountMx(event,this)">$balanceMoney</span>
                </div>
                <input type="hidden" name="subjectId[$mxId]" value="$array[subjectId]">
                <input type="hidden" name="khid[$mxId]" value="$array[khid]">
                <input type="hidden" name="supplierId[$mxId]" value="$array[supplierId]">
                <input type="hidden" name="staffId[$mxId]" value="$array[staffId]">
                <input type="hidden" name="projectId[$mxId]" value="$array[projectId]">
                <input type="hidden" name="materialId[$mxId]" value="$array[materialId]">
                <input type="hidden" name="cashId[$mxId]" value="$array[cashId]">
                <input type="hidden" name="departmentId[$mxId]" value="$array[departmentId]">
          </div>
    </div>
    <div class="cell num-col">
          <div class="num-name $numAccountHide">
              <div><span class="voucher-num-btn">数量：</span><span class="voucher-num-text">{$array['voucherNum']}</span><input name="voucherNum[$mxId]" type="hidden" value="{$array['voucherNum']}"></div>
              <div><span class="voucher-price-btn">单价：</span><span class="voucher-price-text">{$subjectAttr['voucherPrice']}</span><input  name="voucherPrice[$mxId]" type="hidden" value="{$subjectAttr['voucherPrice']}"></div>
          </div>
          <div class="currency-name $currencyAccount">
              <div><span class="voucher-money-btn">{$currency['code']}：</span><span class="voucher-money-text">{$subjectAttr['voucherMoney']}</span><input name="voucherMoney[$mxId]" type="hidden" value="{$subjectAttr['voucherMoney']}"><input name="currencyId[$mxId]" type="hidden" value="{$array['currencyId']}"></div>
              <div><span class="voucher-rate-btn">汇率：</span><span class="voucher-rate-text">{$array['rate']}</span><input class="hide voucher-rate-input"  name="voucherRate[$mxId]" type="hidden" value="{$array['rate']}"></div>
          </div>
    </div>
    <div class="cell jie-col">
        <div class="show_text show_money jie">
            <div class="jie-text $redClass format-line-box">
                $jieMoneyText
            </div>
        </div>
        <input class="money-input hide hide-input jie-input" name="jieMoney[$mxId]"   value="$jieMoney">
    </div>
   <div class="cell dai-col">
        <div class="show_text show_money dai">
            <div class="dai-text $redClass format-line-box">$daiMoneyText</div>
        </div>
        <input class="money-input hide hide-input dai-input" name="daiMoney[$mxId]"   value="$daiMoney">
   </div></div>
eof;
            }
        }

        $all['array'] = $all['array'] ?? [];
        $num          = 12 - count($all['array']);
        for ($i = 1; $i <= $num; $i++) {
            $col_list++;
            $mxId   = suiji();
            $dataTr .= <<<eof
<div class="container-body-row">
    <div class="cell center setting-col"><span>$col_list</span></div>
    <div class="cell oprate-col">
            <img alt="复制此行" title="复制此行" class="copy_v_btn" src="{$this->copyIcon}">
            <img alt="添加一行" title="添加一行" class="add_v_btn" src="{$this->addIco}">
            <img alt="删除此行" title="删除此行" class="del_v_btn" src="{$this->delIco}"> 
    </div>
    <div class="cell summary-col">
            <input name="mxId[]" data-id="$mxId" type="hidden" value="$mxId">
            <div class="summary"></div><textarea class="summary-input hide hide-input" name="summary[$mxId]" type="text" maxlength="220"></textarea>
    </div>
    <div class="cell subject-col">
        <div class="subject-input-parent"><textarea class="subject-input hide hide-input" type="text" maxlength="220"></textarea></div>
        <div class="subject-content subject-text">
            <div class="subject-name"></div>
            <div class="balance hide">
                余额：<span class="balance-money" onclick="accountMx(event,this)">0</span>
            </div>
            <input type="hidden" name="subjectId[$mxId]" value="">
            <input type="hidden" name="khid[$mxId]" value="">
            <input type="hidden" name="supplierId[$mxId]" value="">
            <input type="hidden" name="staffId[$mxId]" value="">
            <input type="hidden" name="projectId[$mxId]" value="">
            <input type="hidden" name="materialId[$mxId]" value="">
            <input type="hidden" name="cashId[$mxId]" value="">
            <input type="hidden" name="departmentId[$mxId]">
        </div>
    </div>
    <div class="cell num-col">
        <div class="num-name hide">
            <div><span class="voucher-num-btn">数量：</span><span class="voucher-num-text">0</span><input name="voucherNum[$mxId]" type="hidden" value=""></div>
            <div><span class="voucher-price-btn">单价：</span><span class="voucher-price-text">0</span><input  name="voucherPrice[$mxId]" type="hidden" value=""></div>
        </div>
        <div class="currency-name hide">
            <div><span class="voucher-money-btn"></span><span class="voucher-money-text">0</span><input name="voucherMoney[$mxId]" type="hidden" value=""><input name="currencyId[$mxId]" type="hidden" value=""></div>
            <div><span class="voucher-rate-btn">汇率：</span><span class="voucher-rate-text">0</span><input class="hide voucher-rate-input"  name="voucherRate[$mxId]" type="hidden" value=""></div>
        </div>
    </div>
    <div class="cell jie-col">
        <div class="show_text show_money jie">
        <div class="jie-text format-line-box">
            <div class="format-line"></div>
            <div class="format-line"></div>
            <div class="format-line"></div>
            <div class="format-line l-blue"></div>
            <div class="format-line"></div>
            <div class="format-line"></div>
            <div class="format-line l-blue"></div>
            <div class="format-line"></div>
            <div class="format-line"></div>
            <div class="format-line pink"></div>
            <div class="format-line"></div>
        </div>
        </div>
        <input class="money-input hide hide-input jie-input" name="jieMoney[$mxId]"   value="">
    </div>
    <div class="cell dai-col">
        <div class="show_text show_money dai">
            <div class="dai-text format-line-box">
                <div class="format-line"></div>
                <div class="format-line"></div>
                <div class="format-line"></div>
                <div class="format-line l-blue"></div>
                <div class="format-line"></div>
                <div class="format-line"></div>
                <div class="format-line l-blue"></div>
                <div class="format-line"></div>
                <div class="format-line"></div>
                <div class="format-line pink"></div>
                <div class="format-line"></div>
            </div>
        </div>
        <input class="money-input hide hide-input dai-input" name="daiMoney[$mxId]"   value="">
    </div>
</div>
eof;
        }
        $jieTotalMoney = round($jieTotalMoney, 2);
        $daiTotalMoney = round($daiTotalMoney, 2);
        $jieTotalMoney = self::yuanToCent($jieTotalMoney);
        $daiTotalMoney = self::yuanToCent($daiTotalMoney);
        $moneyCn       = self::num_to_rmb(self::centToYuan($jieTotalMoney));
        $daiTotalMoney = self::splitNumber($daiTotalMoney);
        $jieTotalMoney = self::splitNumber($jieTotalMoney);
//        $info['voucherNo'] = $info['voucherNo'] ?: 1;
        $this->settingIcon = $this->settingIcon . '?v=' . version;
        //反算规则
        $rateAndMoney = $this->voucherSetting('rateAndMoney') ?: 'money';
        $numAndPrice  = $this->voucherSetting('numAndPrice') ?: 'price';
        $voucher      = query(self::table, "id = '$id'");
        $cancelButton = "<span class='spanButton' onclick=\"layer('voucherEdit', 'templateSave', {})\">存为模板</span>";
        if ($voucher['id']) {
            $cancelButton .= "<span class='spanButton' onclick=\"location.href=root+'control/adIndex.html?cla=voucherEdit&fun=home&method=redChong&id=$id'\">红冲</span>";
            if ($this->power('voucher', 'cancel')) {
                $cancelButton .= "<span class='spanButton' onclick=\"layer('voucher','cancelV',{id:'{$voucher['id']}'})\">作废</span>";
                if ($voucher['workFlow'] == '已作废') {
                    $cancelButton .= "<span class='spanButton' onclick=\"layer('voucher','cancelV',{id:'{$voucher['id']}'})\">取消作废</span>";
                }
            }
        }
        $fileNum = find(['table' => 'file', 'single' => "targetId = '$voucher[id]' and targetId !=''", 'field' => "ifnull(count(id),0) as num"])['num'];
        if ($fileNum > 0) {
            $fileNum = $fileNum . '个';
        } else {
            $fileNum = '';
        }
        $topButton    = <<<eof
<div class="input-div">
    {$wordSelect}&nbsp;字第&nbsp;<input id="voucherNo" class="voucherNo" $disabled $readonly name="voucherNo" type="number" min="1" value="{$voucherNo}">&nbsp;号 <span style="margin-left: 20px">日期：{$recordDate}</span>
    <span style="margin-right: 10px">附单据&nbsp;<input class="voucherNo" $disabled name="receiptNum" min="0" type="number" value="{$info['receiptNum']}">&nbsp;张</span>
    <span style="padding: 2px" class="del-row-button"   onclick="layer('voucherEdit','attachFile',{id:'$id',isEnd:'$isEnd'})">附件</span><span style="margin-right: 10px" class="attach-file-num">$fileNum</span>
    <span style="padding: 2px;margin-right: 10px;position: relative" class="del-row-button" id="text-btn">备注<textarea id="text-input" class="text-input hide" name="text" type="text" maxlength="255">{$info['text']}</textarea></span>
    <a class="del-row-button" title="记账帮助" style="padding: 2px;"  target="_blank" href="$helpUrl">会计准则</a>
</div>
eof;
        $data['html'] = <<<efo
<form name="voucherForm">
<div class="voucher-body">
<div class="subject-selector hide">
            <div class="subject-tabs">
                <div class="tab-item active">全部</div>
                <div class="tab-item">资产</div>
                <div class="tab-item">负债</div>
                <div class="tab-item">权益</div>
                <div class="tab-item">成本</div>
                <div class="tab-item">损益</div>
            </div>
            <div class="subject-box"></div>
            <div onclick="addSubject()"  title="添加科目" class="add_subject_button del-row-button">+添加</div>
</div>
<div class="currency-assit">
     <div class="currency-assit-ul"></div>
     <div class="auxiliary-accounting-button">
        <input type="button" value="取消" onclick="hideCurrency()">
        <input type="button" value="确定" onclick="confirmCurrency()" class="confirm-button">
    </div>
</div>
<div class="calendarBody" data-r="$rateAndMoney" data-n="$numAndPrice">
{$topButton}
<div class="voucher-flex-container">
    <div class="container-header">
        <div class="cell center setting-col"><img onclick="layer('voucherEdit', 'voucherNumAdd', {})" alt="设置" title="设置" style="cursor: pointer" src="{$this->settingIcon}"></div>
        <div class="cell oprate-col">$shortCutButton $useTemplateButton $printButton</div>
        <div class="cell summary-col">摘要</div>
        <div class="cell subject-col">科目</div>
        <div class="cell num-col">数量/外币</div>
        <div class="cell jie-col">
            <div class="center">借方金额</div>
                <div class="moneyUnit format-line-box">
                    <div class="format-line">亿</div>
                    <div class="format-line">千</div>
                    <div class="format-line">百</div>
                    <div class="format-line l-blue">十</div>
                    <div class="format-line">万</div>
                    <div class="format-line">千</div>
                    <div class="format-line l-blue">百</div>
                    <div class="format-line">十</div>
                    <div class="format-line">元</div>
                    <div class="format-line pink">角</div>
                    <div class="format-line">分</div>
                </div>
        </div>
        <div class="cell dai-col">
             <div class="center">贷方金额</div>
             <div class="moneyUnit format-line-box">
                    <div class="format-line">亿</div>
                    <div class="format-line">千</div>
                    <div class="format-line">百</div>
                    <div class="format-line l-blue">十</div>
                    <div class="format-line">万</div>
                    <div class="format-line">千</div>
                    <div class="format-line l-blue">百</div>
                    <div class="format-line">十</div>
                    <div class="format-line">元</div>
                    <div class="format-line pink">角</div>
                    <div class="format-line">分</div>
             </div>
        </div>
        <div class="scroll-bar-col"></div>
    </div>
    <div class="container-body" id="container-body">
            $dataTr
    </div>
    <div class="container-foot">
        <div class="container-body-row">
            <div class="cell center heji-col"><div class="upper-money-total">合计：<span>{$moneyCn}</span></div></div>
            <div class="cell jie-col">
              <div class="show_text show_money">
                  <div class="jie-text jie-total $redClass format-line-box">
                    $jieTotalMoney
                </div>
              </div>
            </div>
            <div class="cell dai-col">
                <div class="show_text show_money">
                    <div class="dai-text dai-total $redClass format-line-box">
                        $daiTotalMoney
                    </div>
                </div>
            </div>
            <div class="scroll-bar-col"></div>
        </div>
    </div>
    <div class="voucher-button container-tail">
         <div><span style="">制单人：{$staffName}</span></div>
         <div>
            $saveBtn{$cancelButton}{$directionButton}
         </div>
    </div>
</div>
<div>
    <input name="id" value="$id" type="hidden">
    <input name="sourceId" value="$sourceId" type="hidden">
    <input type="hidden" name="source" value="$source">
    <div id="file-list" class="hide file-list"></div>    
</div>
</div>
</div>
</form>
efo;
        return $data['html'];
    }

    /**
     * 记账凭证
     * @return string
     */
    public function room(): string
    {
        $param        = [
            'method'    => $this->get('method'),
            'id'        => $this->get('id') ?: suiji(),
            'month'     => $this->get('month'),
            'settingId' => $this->get('settingId'),
            'sourceId'  => $this->get('sourceId'),
        ];
        $data['html'] = $this->voucherHtml($param);
        $data['html'] .= $this->css();
        $data['html'] .= $this->js();
        //返回
        $data['pageType'] = 'list';
        $info             = query(self::table, "id = '$param[id]'");
        $voucherWord      = query('voucher_word', "id = '$info[voucherWordId]'");
        $data['title']    = $info['id'] ? $voucherWord['word'] . $info['voucherNo'] : '新增凭证';
        return $this->tab($data);
    }

    public function showNextVoucher(): bool|string
    {
        $type          = $this->post('type');
        $id            = $this->post('id');
        $voucherWordId = $this->post('voucherWordId');
        $voucherNo     = $this->post('voucherNo');
        $recordDate    = $this->post('recordDate');
        if (empty($type)) {
            $json['warn'] = '未找到类型';
        } elseif (!in_array($type, ['next', 'pre'])) {
            $json['warn'] = '跳转类型错误';
        } elseif (empty($voucherNo) || empty($voucherWordId)) {
            $json['warn'] = '未找到凭证号';
        } elseif (empty($recordDate)) {
            $json['warn'] = '未选择日期';
        } else {
            if ($type == 'pre') {
                $next = find(array('table' => self::table, 'single' => "coid = '" . self::$coid . "' and recordDate = '$recordDate' and voucherNo < '$voucherNo' and voucherWordId = '$voucherWordId' and id !='$id' order by voucherNo desc"));
                if (empty($next['id'])) {
                    $next = find(array('table' => self::table, 'single' => "coid = '" . self::$coid . "' and recordDate < '$recordDate'  and id !='$id' and voucherWordId = '$voucherWordId'  order by recordDate desc,voucherNo desc"));
                }
            } else {
                $next = find(array('table' => self::table, 'single' => "coid = '" . self::$coid . "' and recordDate = '$recordDate' and voucherNo >'$voucherNo' and voucherWordId = '$voucherWordId' and id !='$id' order by voucherNo asc"));
                if (empty($next['id'])) {
                    $next = find(array('table' => self::table, 'single' => "coid = '" . self::$coid . "' and recordDate > '$recordDate' and voucherWordId = '$voucherWordId'  and id !='$id' order by recordDate asc,voucherNo asc"));
                }
            }
            if (!isset($next['id']) || empty($next['id'])) {
                $json['warn'] = '没有下一张凭证了';
            } else {
                $json['href'] = root . 'control/adIndex.html?cla=voucherEdit&fun=room&id=' . $next['id'];
                $json['warn'] = 2;

            }
        }
        return json_encode($json, 320);
    }

    /**
     * 判断是否有下一张凭证
     * @param $recordDate
     * @param $voucherNo
     * @param $voucherWordId
     * @return bool
     */
    public function isNext($recordDate, $voucherNo, $voucherWordId): bool
    {
        $next = find(array('table' => self::table, 'single' => "coid = '" . self::$coid . "' and recordDate = '$recordDate' and voucherNo >'$voucherNo' and voucherWordId = '$voucherWordId'  order by voucherNo asc"));
        if (empty($next['id'])) {
            $next = find(array('table' => self::table, 'single' => "coid = '" . self::$coid . "' and recordDate > '$recordDate' and voucherWordId = '$voucherWordId'  order by recordDate asc,voucherNo asc"));
        }
        if (!isset($next['id']) || empty($next['id'])) {
            return false;
        }
        return true;
    }

    /**
     * 判断是否有上一张凭证
     * @param $recordDate
     * @param $voucherNo
     * @param $voucherWordId
     * @return bool
     */
    public function isPre($recordDate, $voucherNo, $voucherWordId): bool
    {
        $next = find(array('table' => self::table, 'single' => "coid = '" . self::$coid . "' and recordDate = '$recordDate' and voucherNo < '$voucherNo' and voucherWordId = '$voucherWordId' order by voucherNo desc"));
        if (empty($next['id'])) {
            $next = find(array('table' => self::table, 'single' => "coid = '" . self::$coid . "' and recordDate < '$recordDate'  and voucherWordId = '$voucherWordId'  order by recordDate desc,voucherNo desc"));
        }
        if (!isset($next['id']) || empty($next['id'])) {
            return false;
        }
        return true;
    }

    /**
     * 计算金额
     */
    public function calculateMoney($subjectId, $rule, $month)
    {
        $where = '';
        if ($subjectId) {
            $where = " and subjectId = '$subjectId'";
        }
        $money = 0;
        switch ($rule) {
            case '应发工资':
                $sum   = find(array('table' => 'work_sign_record', 'single' => "month = '$month' and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(baseMoney+jobMoney+performance+fullAttendance-decMoney),0) as money"));
                $money = $sum['money'];
                break;
            case '实发工资':
                $sum   = find(array('table' => 'work_sign_record', 'single' => "month = '$month' and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(payMoney),0) as money"));
                $money = $sum['money'];
                break;
            case '考勤扣款':
                $sum   = find(array('table' => 'work_sign_record', 'single' => "month = '$month' and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(decMoney),0) as money"));
                $money = $sum['money'];
                break;
            case '个人养老保险':
                $sum   = find(array('table' => 'insure', 'single' => "moon = '$month' and subject = '养老保险'  and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(personal),0) as money"));
                $money = $sum['money'];
                break;
            case '个人医疗保险':
                $sum   = find(array('table' => 'insure', 'single' => "moon = '$month' and subject = '基本医疗' and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(personal),0) as money"));
                $money = $sum['money'];
                break;
            case '个人失业保险':
                $sum   = find(array('table' => 'insure', 'single' => "moon = '$month' and subject = '失业保险' and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(personal),0) as money"));
                $money = $sum['money'];
                break;
            case '个人工伤保险':
                $sum   = find(array('table' => 'insure', 'single' => "moon = '$month' and subject = '工伤保险'  and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(personal),0) as money"));
                $money = $sum['money'];
                break;
            case '个人生育保险':
                $sum   = find(array('table' => 'insure', 'single' => "moon = '$month' and subject = '生育保险'  and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(personal),0) as money"));
                $money = $sum['money'];
                break;
            case '公司养老保险':
                $sum   = find(array('table' => 'insure', 'single' => "moon = '$month' and subject = '养老保险' and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(company+fund),0) as money"));
                $money = $sum['money'];
                break;
            case '公司医疗保险':
                $sum   = find(array('table' => 'insure', 'single' => "moon = '$month' and subject = '基本医疗' and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(company+fund),0) as money"));
                $money = $sum['money'];
                break;
            case '公司工伤保险':
                $sum   = find(array('table' => 'insure', 'single' => "moon = '$month' and subject = '工伤保险' and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(company+fund),0) as money"));
                $money = $sum['money'];
                break;
            case '公司生育保险':
                $sum   = find(array('table' => 'insure', 'single' => "moon = '$month' and subject = '生育保险' and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(company+fund),0) as money"));
                $money = $sum['money'];
                break;
            case '公司失业保险':
                $sum   = find(array('table' => 'insure', 'single' => "moon = '$month' and subject = '失业保险' and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(company+fund),0) as money"));
                $money = $sum['money'];
                break;
            case '代扣个人所得税':
                $sum   = find(array('table' => 'work_sign_record', 'single' => "month = '$month' and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(personalTax),0) as money"));
                $money = $sum['money'];
                break;
            case '公司住房公积金':
                $sum   = find(array('table' => 'provident_fund', 'single' => "month = '$month' and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(companyFund),0) as money"));
                $money = $sum['money'];
                break;
            case '个人住房公积金':
                $sum   = find(array('table' => 'provident_fund', 'single' => "month = '$month' and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(personFund),0) as money"));
                $money = $sum['money'];
                break;
            case '实发工资调整':
                $sum   = find(array('table' => 'work_sign_record', 'single' => "month = '$month' and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(adjustmentMoney),0) as money"));
                $money = $sum['money'];
                break;
            case '奖金':
                $sum   = find(array('table' => 'work_sign_record', 'single' => "month = '$month' and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(fullAttendance),0) as money"));
                $money = $sum['money'];
                break;
            case '应付职工薪酬':
                $sum = find(array('table' => 'work_sign_record', 'single' => "month = '$month' and isPay = 0 and stid in (select stid from staff where 1=1 $where)", 'field' => "ifnull(sum(money),0) as money"));
                //找当月的奖惩金额
                $rewards = find(['table' => 'rewards', 'where' => "staffId in (select stid from work_sign_record where month = '$month' and isPay = 0) and date_format(recordDate,'%Y-%m') ='$month' and state = '已通过'", 'sum' => "money"]);
                //社保扣款(找缴款月份为这个月的)
                $insure = find(array('table' => 'insure', 'single' => "payMoon = '$month' and stid in (select stid from work_sign_record where month = '$month' and isPay = 0)", 'field' => "ifnull(sum(personal),0) as personal"));
                //公积金扣款
                $providentFund = find(array('table' => 'provident_fund', 'single' => "month = '$month' and isCommit = 1 and staffId in (select stid from work_sign_record where month = '$month' and isPay = 0)", 'field' => "ifnull(sum(decMoney),0) as decMoney"));
                //个税扣款
                $personalTax = find(array('table' => 'personal_tax', 'single' => "month = '$month' and isCommit = 1 and staffId in (select stid from work_sign_record where month = '$month' and isPay = 0)", 'field' => "ifnull(sum(decMoney),0) as decMoney"));
                $money       = round($sum['money'] + $rewards - $insure['personal'] - $providentFund['decMoney'] - $personalTax['decMoney'], 2);
                break;
        }
        return $money;
    }

    /**
     * 金额小写转大写
     * @param $num
     * @return string
     */
    public static function num_to_rmb($num): string
    {
        if ($num == '') {
            return '';
        }
        $c1 = "零壹贰叁肆伍陆柒捌玖";
        $c2 = "分角元拾佰仟万拾佰仟亿";
        //精确到分后面就不要了，所以只留两个小数位
        $num = round($num, 2);
        //将数字转化为整数
        $num = $num * 100;
        if (strlen($num) > 10) {
            return "金额太大，请检查";
        }
        $i = 0;
        $c = "";
        while (1) {
            if ($i == 0) {
                //获取最后一位数字
                $n = substr($num, strlen($num) - 1, 1);
            } else {
                $n = $num % 10;
            }
            //每次将最后一位数字转化为中文
            $p1 = substr($c1, 3 * $n, 3);
            $p2 = substr($c2, 3 * $i, 3);
            if ($n != '0' || (($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
                $c = $p1 . $p2 . $c;
            } else {
                $c = $p1 . $c;
            }
            $i = $i + 1;
            //去掉数字最后一位了
            $num = $num / 10;
            $num = (int)$num;
            //结束循环
            if ($num == 0) {
                break;
            }
        }
        $j    = 0;
        $slen = strlen($c);
        while ($j < $slen) {
            //utf8一个汉字相当3个字符
            $m = substr($c, $j, 6);
            //处理数字中很多0的情况,每次循环去掉一个汉字“零”
            if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
                $left  = substr($c, 0, $j);
                $right = substr($c, $j + 3);
                $c     = $left . $right;
                $j     = $j - 3;
                $slen  = $slen - 3;
            }
            $j = $j + 3;
        }
        //这个是为了去掉类似23.0中最后一个“零”字
        if (substr($c, strlen($c) - 3, 3) == '零') {
            $c = substr($c, 0, strlen($c) - 3);
        }
        //将处理的汉字加上“整”
        if (empty($c)) {
            return "零元整";
        } else {
            return $c . "整";
        }
    }

    public function js(): string
    {
        $rotateJs = root . 'static/javascript/jquery.rotate.js';
        $jsSrc    = root . 'static/javascript/voucher-edit.js?v=' . version;
        return <<<eof
<script type="text/javascript" src="$rotateJs"></script>
<script type="text/javascript" src="$jsSrc"></script>
eof;
    }

    public function getVoucherNo()
    {
        $json['voucherNo'] = self::voucherNo($this->post('voucherWordId'), $this->post('recordDate'));
        return json_encode($json, 320);
    }

    /**
     * 原始文件拍照
     * @return false|string
     */
    public function photograph()
    {
        $failIco = root . 'img/control/app_stop.jpg';
//        $rotate = root.'img/control/rotate.svg';
        //  <img title="旋转" alt="旋转" src="{$rotate}" onclick="roateImg()" style="width: 20px;margin-left: 20px;cursor: pointer;margin-top: -2px" id="rotate">
        //生成表单
        $html = <<<eof
<form name="photographForm">
<div class="photograph-body" onLoad="Init()">
    <div class="photograph-left">
        <div>
            <span class="spanButton li-btn-blue-bg" style="margin-left: 0" onclick="GrabImageBase64()">拍摄照片</span>
            <span style="margin-left: 20px"><label class="checkbox"><input type="checkbox" name="cutpage" value="cutpage" checked><span></span>&nbsp;裁剪页面</label></span>
          
        </div>
        <div style="margin-top: 20px">
            <p class="xform-p"></p>
            <p id="streamwrap" class="xform-p">
            <img id="streamimage" class="xform" src="http://127.0.0.1:38088/video=stream&camidx=0" onerror="onerror=null;src='$failIco'"/>
            </p>
        </div>
    </div>
    <div class="photograph-right">
        <div><span class="spanButton li-btn-blue-bg" onclick="commitPhotograph('photographForm',root+'control/adIndex.html?cla=voucherEdit&fun=photographEdit')">确定</span></div>
        <div class="picture-list">
             
        </div>
    </div>
</div>
</form>
<style>

.photograph-body{display: flex;flex-direction: row}
.photograph-left{padding: 10px}
.photograph-right{width: 100%;padding: 10px;border-left: 1px solid #dadada}
.picture-list img{width: 200px;}
.picture-list{overflow-y: scroll;height: 455px;margin-top: 5px;text-align: center}
#streamimage{width: 430px;height: 430px}
img.x-rotated-0 {}
img.x-rotated-90 {
	-moz-transform: rotate(90deg);
	-webkit-transform: rotate(90deg);
}
img.x-rotated-180 {
	-moz-transform: rotate(180deg);
	-webkit-transform: rotate(180deg);
}
img.x-rotated-270 {
	-moz-transform: rotate(270deg);
	-webkit-transform: rotate(270deg);
}
img.x-mirrored-rotated-0 {
	-moz-transform: scaleX(-1);
	-webkit-transform: scaleX(-1);
}
img.x-mirrored-rotated-90 {
	-moz-transform: rotate(90deg) scaleX(-1);
	-webkit-transform: rotate(90deg) scaleX(-1);
}
img.x-mirrored-rotated-180 {
	-moz-transform: rotate(180deg) scaleX(-1);
	-webkit-transform: rotate(180deg) scaleX(-1);
}
img.x-mirrored-rotated-270 {
	-moz-transform: rotate(270deg) scaleX(-1);
	-webkit-transform: rotate(270deg) scaleX(-1);
}
img.x-flipped-rotated-0 {
	-moz-transform: scaleY(-1);
	-webkit-transform: scaleY(-1);
}
img.x-flipped-rotated-90 {
	-moz-transform: rotate(90deg) scaleY(-1);
	-webkit-transform: rotate(90deg) scaleY(-1);
}
img.x-flipped-rotated-180 {
	-moz-transform: rotate(180deg) scaleY(-1);
	-webkit-transform: rotate(180deg) scaleY(-1);
}
img.x-flipped-rotated-270 {
	-moz-transform: rotate(270deg) scaleY(-1);
	-webkit-transform: rotate(270deg) scaleY(-1);
}
img.x-flipped-mirrored-rotated-0 {
	-moz-transform: scale(-1,-1);
	-webkit-transform: scale(-1,-1);
}
img.x-flipped-mirrored-rotated-90 {
	-moz-transform: rotate(90deg) scale(-1,-1);
	-webkit-transform: rotate(90deg) scale(-1,-1);
}
img.x-flipped-mirrored-rotated-180 {
	-moz-transform: rotate(180deg) scale(-1,-1);
	-webkit-transform: rotate(180deg) scale(-1,-1);
}
img.x-flipped-mirrored-rotated-270 {
	-moz-transform: rotate(270deg) scale(-1,-1);
	-webkit-transform: rotate(270deg) scale(-1,-1);
}
</style>
eof;

        //返回
        return $this->layer(array("title" => "拍照", 'winFix' => true, "height" => 600, "width" => 845, "html" => $html, "button" => false));
    }

    /**
     * 高拍仪数据处理
     */
    public function photographEdit(): bool|string
    {
        $fileCodes = $this->post('fileCode');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (static::is_null_array($fileCodes)) {
            $json['warn'] = '未找到上传文件';
        } else {
            $json['warn'] = 2;
            $x            = 0;
            $url          = 'file/' . self::page . "/" . date("Ym");
            $this->_mkdir($url);
            $html = '';
            foreach ($fileCodes as $base64) {
                if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $res)) {
                    $suiji = suiji();
                    $src   = $url . "/" . $suiji . ".jpg"; //保存附件的根目录路径
                    if (file_put_contents(serverRoot . $src, base64_decode(str_replace($res[1], '', $base64)))) {
                        $field = array('id' => suiji(), 'stid' => $this->control['stid'], 'target' => '财务凭证', 'name' => '财务凭证' . $suiji . '.jpg', 'format' => 'jpg', 'size' => filesize(serverRoot . $src), 'src' => $src);
                        $warn  = insert(array('table' => 'file', 'field' => $field));
                        if ($warn == '新增成功') {
                            $x++;
                            $html .= "<input name='fileId[]' type='hidden' value='{$field['id']}' />";
                        }
                    }
                }
            }
            $json['html']    = $html;
            $json['success'] = $x;
        }
        return json_encode($json, 320);
    }

    /**
     * 添加一行
     */
    public function addRow(): bool|string
    {
        $jieTotal       = $this->post('jieMoney');
        $daiTotal       = $this->post('daiMoney');
        $jieNum         = $this->post('jieNum');
        $daiNum         = $this->post('daiNum');
        $direction      = $this->post('direction');
        $summary        = $this->post('summary');
        $daiBalance     = $jieBalance = 0;
        $jieBalanceText = $daiBalanceText = '';
        if ($jieTotal > $daiTotal) {
            $daiBalance     = $jieTotal - $daiTotal;
            $daiBalanceText = self::yuanToCent($daiBalance);
        } elseif ($jieTotal < $daiTotal) {
            $jieBalance     = $daiTotal - $jieTotal;
            $jieBalanceText = self::yuanToCent($jieBalance);
        }
//        if ($jieNum > 0 || $daiNum > 0) {
//            if ($direction == '借') {
//
//            } else if ($direction == '贷') {
//
//            }
//        }
        $jieBalanceText = self::splitNumber($jieBalanceText);
        $daiBalanceText = self::splitNumber($daiBalanceText);
        $mxId           = suiji();
        $json['html']   = <<<eof
<div class="container-body-row">
    <div class="cell center setting-col"><span></span></div>
    <div class="cell oprate-col">
        <img alt="复制此行" title="复制此行" class="copy_v_btn"  src="{$this->copyIcon}">
        <img alt="添加一行" title="添加一行" class="add_v_btn" src="{$this->addIco}">
        <img alt="删除此行" title="删除此行" class="del_v_btn" src="{$this->delIco}"> 
    </div>
    <div class="cell summary-col">
        <input name="mxId[]" data-id="$mxId" type="hidden" value="$mxId">
        <div class="summary">$summary</div><textarea class="summary-input hide hide-input" name="summary[$mxId]" type="text" maxlength="220">$summary</textarea>
    </div>
    <div class="cell subject-col">
        <div class="subject-input-parent">
                <textarea class="subject-input hide hide-input" type="text"></textarea>
            </div>
            <div class="subject-content subject-text">
                <div class="subject-name"></div>
                <div class="balance hide">
                    余额：<span class="balance-money" onclick="accountMx(event,this)">0</span>
                </div>
                <input type="hidden" name="subjectId[$mxId]" value="">
                <input type="hidden" name="khid[$mxId]" value="">
                <input type="hidden" name="supplierId[$mxId]" value="">
                <input type="hidden" name="staffId[$mxId]" value="">
                <input type="hidden" name="projectId[$mxId]" value="">
                <input type="hidden" name="materialId[$mxId]" value="">
                <input type="hidden" name="cashId[$mxId]" value="">
                 <input type="hidden" name="departmentId[$mxId]" value="">
            </div>
    </div>
    <div class="cell num-col">
        <div class="num-name hide">
            <div><span class="voucher-num-btn">数量：</span><span class="voucher-num-text">0</span><input name="voucherNum[$mxId]" type="hidden" value=""></div>
            <div><span class="voucher-price-btn">单价：</span><span class="voucher-price-text">0</span><input  name="voucherPrice[$mxId]" type="hidden" value=""></div>
        </div>
        <div class="currency-name hide">
            <div><span class="voucher-money-btn"></span><span class="voucher-money-text">0</span><input name="voucherMoney[$mxId]" type="hidden" value=""><input name="currencyId[$mxId]" type="hidden" value=""></div>
            <div><span class="voucher-rate-btn">汇率：</span><span class="voucher-rate-text">0</span><input class="hide voucher-rate-input"  name="voucherRate[$mxId]" type="hidden" value=""></div>
        </div>
    </div>
    <div class="cell jie-col">
        <div class="show_text show_money jie">
            <div class="jie-text format-line-box">
                $jieBalanceText
            </div>
        </div>
        <input class="money-input hide hide-input jie-input" name="jieMoney[$mxId]"  value="$jieBalance">
    </div>
    <div class="cell dai-col">
        <div class="show_text show_money dai">
            <div class="dai-text format-line-box">
                $daiBalanceText
            </div>
        </div>
        <input class="money-input hide hide-input dai-input" name="daiMoney[$mxId]"   value="$daiBalance"></div>
    </div>
</div>
<script>
$("[data-id='$mxId']").parent().parent().find(".summary-input").each(function() {
        $(this).bigAutocomplete({
            // width:543,
              body: 'voucher-body',
              sign:'voucherSummary',
                markPage: 'voucherEdit',//特殊页面
            url:root + 'control/adIndex.html?cla=voucherEdit&fun=getSummary',
            callback:function(data,e){
                $(e).val(data.title);
                $(e).parent().find(".summary").text(data.title);
                 //触发切换列
                enterFoucus($(e).parent().find(".summary"),1)
            }
        });
    })
</script>
eof;
        return json_encode($json, 320);
    }

    public function css()
    {
        $fontSize = $this->voucherSetting('fontSize') ?: '12';
        $root     = root;
        $version  = version;
        return <<<eof
<link href="{$root}static/stylesheet/voucher-css.css?v=$version" rel="stylesheet">
<style>
.voucher-flex-container textarea{font-size: {$fontSize}px}
</style>
eof;

    }

    public function subject($workFlow = '资产'): bool|string
    {
        $mxId    = $this->post('mxId');
        $compint = new componentClass();

        $data         = [
            "id"   => 'voucherEditMode',//需要编辑
            "menu" => subjectClass::enterpriseSubjectTab()
        ];
        $data['html'] = $compint->subjectContent($workFlow, true);
        $hidden       = hidden(array('name' => 'mxId', 'value' => $mxId));
        $html         = $compint->tabRewrite($data) . $hidden . "<div style='padding: 0 20px'><input name='chooseId' value='' type='hidden'><input name='chooseName' value='' type='hidden'><input type='button' onclick=\"confirmSubjectId('{$mxId}')\" class='button right confirm' value='确认'>&emsp;<input type='button' class='button right cancel' onclick=\"$('#voucherEditSubject').hide()\" value='取消'></div>";

        return $this->layer(array("title" => "科目选择器", "height" => 600, "width" => 600, "html" => $html));

    }

    /**
     * 模糊查询科目
     */
    public function getSubject(): bool|string
    {
        $val          = $this->post('keyword');//关键词
        $showParent   = (bool)$this->post('showParent');
        $json['data'] = [];
        $where        = " and coid='" . self::$coid . "' and state = '启用'";
        if ($val) {
            $where .= " and (name like '%$val%' or code like '%$val%' or concat(code,' ',name) like '%$val%')";
        }
        $all        = find(array('table' => 'subject', 'where' => "1=1 $where order by code asc"));
        $resArr     = componentClass::subjectSort($all['array'], $showParent);
        $subjectAll = [];
        foreach ($resArr as $array) {
            $title = $array['code'] . ' ' . subjectClass::getName($array['id']);
            if ($array['assistAccount'] == '是') {
                $title .= "<span class='yellow' style='padding-left: 2px;font-weight: bold'>辅</span>";
            }
            if ($array['currencyAccount'] == '是') {
                $title .= "<span class='yellow' style='padding-left: 2px;font-weight: bold'>外</span>";
            }
            $subjectAll['all'][] = array('title' => $title, 'value' => $array['code'] . ' ' . subjectClass::getName($array['id']), 'direction' => $array['direction'], 'assistAccount' => $array['assistAccount'], 'numAccount' => $array['numAccount'], 'currencyAccount' => $array['currencyAccount'], 'id' => $array['id']);
            switch ($array['type']) {
                case '资产类':
                    $subjectAll['asset'][] = array('title' => $title, 'value' => $array['code'] . ' ' . subjectClass::getName($array['id']), 'direction' => $array['direction'], 'assistAccount' => $array['assistAccount'], 'numAccount' => $array['numAccount'], 'currencyAccount' => $array['currencyAccount'], 'id' => $array['id']);
                    break;
                case '负债类':
                    $subjectAll['debt'][] = array('title' => $title, 'value' => $array['code'] . ' ' . subjectClass::getName($array['id']), 'direction' => $array['direction'], 'assistAccount' => $array['assistAccount'], 'numAccount' => $array['numAccount'], 'currencyAccount' => $array['currencyAccount'], 'id' => $array['id']);
                    break;
                case '损益类':
                    $subjectAll['loss'][] = array('title' => $title, 'value' => $array['code'] . ' ' . subjectClass::getName($array['id']), 'direction' => $array['direction'], 'assistAccount' => $array['assistAccount'], 'numAccount' => $array['numAccount'], 'currencyAccount' => $array['currencyAccount'], 'id' => $array['id']);
                    break;
                case '成本类':
                    $subjectAll['cost'][] = array('title' => $title, 'value' => $array['code'] . ' ' . subjectClass::getName($array['id']), 'direction' => $array['direction'], 'assistAccount' => $array['assistAccount'], 'numAccount' => $array['numAccount'], 'currencyAccount' => $array['currencyAccount'], 'id' => $array['id']);
                    break;
                case '权益类':
                    $subjectAll['interests'][] = array('title' => $title, 'value' => $array['code'] . ' ' . subjectClass::getName($array['id']), 'direction' => $array['direction'], 'assistAccount' => $array['assistAccount'], 'numAccount' => $array['numAccount'], 'currencyAccount' => $array['currencyAccount'], 'id' => $array['id']);
                    break;
                case '共同类':
                    $subjectAll['common'][] = array('title' => $title, 'value' => $array['code'] . ' ' . subjectClass::getName($array['id']), 'direction' => $array['direction'], 'assistAccount' => $array['assistAccount'], 'numAccount' => $array['numAccount'], 'currencyAccount' => $array['currencyAccount'], 'id' => $array['id']);
                    break;
            }
        }
        $subjectTab = subjectClass::enterpriseSubjectTab();
        $tabs       = '';
        foreach ($subjectTab as $value) {
            $tabs .= <<<eof
 <div class="tab-item">{$value}</div>
eof;

        }
        $tabs = <<<eof
    <div class="tab-item active">全部</div>
               $tabs
eof;

        $json['data'] = $subjectAll;
        $json['tabs'] = $tabs;
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 获取科目详细信息
     */
    public function subjectInfo(): bool|string
    {
        $info = query('subject', "id = '" . post('id') . "'");
        if (empty($info['id'])) {
            $json['warn'] = "未找到此科目";
        } else {
            $rmb          = query('currency', "coid = '" . self::$coid . "' and isBase = '是'");
            $json['data'] = [
                'id'              => $info['id'],
                'name'            => subjectClass::getName($info['id']),
                'code'            => $info['code'],
                'numAccount'      => $info['numAccount'],
                'assistAccount'   => $info['assistAccount'],
                'currencyAccount' => $info['currencyAccount'],
                'rate'            => $rmb['accuracy'] > 0 ? $rmb['rate'] / $rmb['accuracy'] : 0,
            ];
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 计算余额
     * @return false|string
     */
    public function culBalance()
    {
        $jieMoney = $this->post('jieMoney');
        $daiMoney = $this->post('daiMoney');
        $mxId     = $this->post('mxId');
        $info     = query('subject', "id = '" . $this->post('id') . "'");
        if (empty($info['id'])) {
            $json['warn'] = "未找到此科目";
        } else {
            $accountDetail = new accountDetailsClass();
            $balance       = $accountDetail->balanceCul($this->post('recordDate') ?: $this->date, $info['id'], '累计', $jieMoney, $daiMoney, explode(',', $this->post('idCollection')), $mxId);
            $balanceMoney  = $balance['balance'];
            $json['data']  = [
                'balanceMoney' => round($balanceMoney, 2) ?: 0,
            ];
            $json['warn']  = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 获取汇率
     */
    public function getRate(): bool|string
    {
        $currency     = query('currency', "id = '" . $this->post('id') . "'");
        $json['data'] = $currency['id'] ? $currency['rate'] / $currency['accuracy'] : 0;
        return json_encode($json, 320);
    }

    /**
     * 保存为模板
     * @return false|string
     */
    public function templateSave()
    {
        //生成表单
        $html = $this->layerEdit(
            array(
                "table"    => array(
                    array(
                        "模板编码：" => voucherModelClass::generateTemplateNo(),
                    ),
                    array(
                        must . "模板类型：" => componentClass::selectText(['name' => 'templateType', 'title' => '模板类型', 'cla' => self::page, 'fun' => 'getVoucherTemplateType']) // "<span style='margin-left: 5px' onclick=\"layer('voucherEdit','templateType',{})\" class='del-row-button'>新建</span>",
                    ),
                    array(
                        must . "模板名称：" => text(array("name" => "templateName", "value" => ''))
                    ),
                    array(
                        "保存金额：" => checkbox(array("name" => "isSaveMoney", "value" => ['1' => '']))
                    )
                ),
                'formName' => 'voucherForm',
                'hidden'   => hidden(['name' => 'id', 'value' => suiji()]),
            )
        );
        //返回
        return $this->layer(array(
            "title"  => "存为模板",
            "height" => 245,
            "width"  => 700,
            "html"   => $html,
            'button' => "<input onclick=\"subForm('voucherForm,voucherEditTemplateSaveForm',root+'control/adIndex.html?cla=voucherModel&fun=templateEdit&from=new')\" type='button' class='button' value='保存'>"
        ));
    }

    public function getVoucherTemplateType()
    {
//        $keyword = $this->post('keyword');//关键词
        $json['data'] = [];
        $array        = para('voucherTemplateType', '，');
        foreach ($array as $val) {
            $json['data'][] = array('title' => $val, 'id' => $val);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 模板类型编辑
     */
    public function templateType(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(
            array(
                "table" => array(
                    [
                        "名称：" => text(['name' => 'typeName']),
                    ],
                )
            )
        );
        //返回
        return $this->layer(array(
            "title"  => "模板类型编辑",
            "height" => 300,
            "width"  => 800,
            "html"   => $html,
            'button' => "<input onclick=\"commitTemp()\" type='button' class='button' value='" . L('button.ConfirmSubmit') . "'>",
        ));

    }

    public function templateTypeEdit()
    {
        $field = [
            'name' => $this->post('type')
        ];
        $array = para('voucherTemplateType', '，');
        if (empty($field['name'])) {
            $json['warn'] = '请填写类型名称';
        } elseif (in_array($field['name'], $array)) {
            $json['warn'] = '已存在此类型名称';
        } else {
            $array[]      = $field['name'];
            $json['warn'] = self::update(array('table' => 'para', 'field' => ['paValue' => implode('，', $array)], 'where' => "paid = 'voucherTemplateType' and paLang = '" . lang . "'"));
            if ($json['warn'] == '更新成功') {
                $json['warn'] = 2;
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 附件上传
     */
    public function attachFile()
    {
        $id    = $this->post('id');
        $isEnd = $this->post('isEnd');
        //生成表单
        //<span class='spanButton' style='margin-left: 0'>从会计电子档案选择</span>
        $html = $this->layerEdit(
            array(
                "table" => array(
                    array(
                        "<span class='small-title'>附件</span>"
                    ),
                    array(
                        fileUploadClass::addFileComponent($id, '财务凭证', 'voucherEdit', 'voucherEditAttachFileForm')
                    )
                )
            )
        );
        //返回
        return $this->layer(array(
            "title"  => "附件",
            "height" => 400,
            "width"  => 800,
            "zindex"  => 100,
            "html"   => $html,
            'button' => $isEnd ? ' ' : "<input onclick=\"saveFile('voucherEditAttachFileForm')\" type='button' class='button' value='保存'>"
        ));
    }

    /**
     * 获取凭证选项设置
     * @param string $type
     * @return mixed|string
     */
    public function voucherSetting($type = 'voucherNumAdd')
    {
        $setting = query('user_setting', "type='凭证设置' and stid = '" . self::$stid . "' and coid = '" . self::$coid . "'");
        if (empty($setting['id'])) {
            return '';
        }
        $settingArr = json_decode($setting['value'], true);
        return $settingArr[$type] ?? '';
    }

    /**
     * 自动补号
     */
    public function voucherNumAdd()
    {
        //生成表单
        $html = $this->layerEdit(
            array(
                "table" => array(
                    array(
                        must . "自动补号：" => radio(array('name' => 'voucherNumAdd', 'value' => ['是' => '是' . componentClass::tipComponent('按凭证字最后一位向后自动补号', '?', class: 'tip-voucher'), '否' => '否'], 'checked' => $this->voucherSetting() ?: '否'))
                    ),
                    array(
                        must . "是否固定日期：" => radio(array('name' => 'fixDate', 'value' => ['是' => "是\n" . text(['name' => 'fixDateValue', 'class' => 'width150 center', 'laydate' => [], 'value' => $this->voucherSetting('fixDateValue') ?: $this->date]) . componentClass::tipComponent('以后录入凭证的日期都默认为当前日期', '?', class: 'tip-voucher') . "&emsp;&emsp;", '否' => '否'], 'checked' => $this->voucherSetting('fixDate') ?: '否'))
                    ),
                    array(
                        must . "字体大小：" => radio(array('name' => 'fontSize', 'value' => ['14' => '小', '16' => '中', '18' => '大'], 'checked' => $this->voucherSetting('fontSize') ?: '12'))
                    ),
                    array(
                        must . "原币汇率金额反算规则：" => radio(array('name' => 'rateAndMoney', 'value' => ['money' => '反算原币' . componentClass::tipComponent('如果已经录入原币数量和汇率，修改金额时，汇率不变，并根据新的金额除以当前汇率获得原币数量', '?', class: 'tip-voucher'), 'rate' => '反算汇率' . componentClass::tipComponent('如果已经录入原币数量和汇率，修改金额时，原币数量不变，并根据新的金额除以当前原币数量获得汇率', '?', class: 'tip-voucher')], 'checked' => $this->voucherSetting('rateAndMoney') ?: 'money'))
                    ),
                    array(
                        must . "数量单价反算规则：" => radio(array('name' => 'numAndPrice', 'value' => ['num' => '反算数量' . componentClass::tipComponent('如果已经录入数量和单价，修改金额时，单价不变，并根据新的金额除以当前单价获得数量', '?', class: 'tip-voucher'), 'price' => '反算单价' . componentClass::tipComponent('如果已经录入数量和单价，修改金额时，数量不变，并根据新的金额除以当前数量获得单价', '?', class: 'tip-voucher')], 'checked' => $this->voucherSetting('numAndPrice') ?: 'price'))
                    ),
                )
            )
        );
        //返回
        return $this->layer(array(
            'zindex' => '11',
            "title"  => "选项",
            "height" => 300,
            "width"  => 590,
            "html"   => $html,
            'button' => "<input onclick=\"voucherNumEdit('voucherEditVoucherNumAddForm',root+'control/adIndex.html?cla=voucherEdit&fun=voucherNumAddEdit')\" type='button' class='button' value='保存'>"
        ));
    }

    /**
     * 修改自动补号
     */
    public function voucherNumAddEdit()
    {
        $field   = [
            'voucherNumAdd' => $this->post('voucherNumAdd'),
            'fixDate'       => $this->post('fixDate'),
            'fixDateValue'  => $this->post('fixDateValue'),
            'fontSize'      => $this->post('fontSize'),
            'rateAndMoney'  => $this->post('rateAndMoney'),
            'numAndPrice'   => $this->post('numAndPrice')
        ];
        $setting = query('user_setting', "type='凭证设置' and stid = '" . self::$stid . "' and coid = '" . self::$coid . "'");
        if (empty($field['voucherNumAdd']) || !in_array($field['voucherNumAdd'], ['是', '否'])) {
            $json['warn'] = '请选择自动补号方式';
        } elseif (empty($field['fixDate']) || !in_array($field['fixDate'], ['是', '否'])) {
            $json['warn'] = '请选择是否固定日期';
        } elseif ($field['fixDate'] == '是' && empty($field['fixDateValue'])) {
            $json['warn'] = '请选择固定日期';
        } else {
            if (empty($setting['id'])) {
                $json['warn'] = insert(array('table' => 'user_setting', 'field' => ['type' => '凭证设置', 'coid' => self::$coid, 'stid' => self::$stid, 'value' => json_encode($field, 320)]));
            } else {
                $json['warn'] = update(array('table' => 'user_setting', 'field' => ['value' => json_encode($field, 320)], 'where' => "id = '$setting[id]'"));
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了凭证选项";
                $this->logText(["type" => self::page, "text" => $text]);
                $json['warn'] = 2;
                $settingArr   = json_decode($setting['value'], true);
                $fontSize     = $settingArr['fontSize'] ?? '';
                $json['data'] = [
                    'fontSize'     => '',
                    'rateAndMoney' => $field['rateAndMoney'],
                    'numAndPrice'  => $field['numAndPrice'],
                ];
                if ($fontSize != $field['fontSize']) {
                    $json['data']['fontSize'] = $field['fontSize'];
                    $json['msg']              = '修改成功';
                }

            }
        }
        return json_encode($json, 320);
    }


    public function getCurrencyAssit()
    {
        $mxId  = $this->post('mxId');
        $price = $this->post('price');
        $money = $this->post('money');
        $rate  = $this->post('rate');
        $num   = $this->post('num');

        $subject  = query('subject', "id = '" . $this->post('subjectId') . "'");
        $itemHtml = '';
        if ($subject['numAccount'] == '是') {
            $itemHtml .= <<<eof
<div class="account-item">
        <div class="account-item-title">数量：</div>
        <div class="account-item-value"><input name="numAsset" type="text" value="$num"></div>
</div>
<div class="account-item">
        <div class="account-item-title">单价：</div>
        <div class="account-item-value"><input name="priceAsset" type="text" value="$price"></div>
</div>
eof;

        }
        if ($subject['currencyAccount'] == '是') {
            $currency = query('currency', "id = '$subject[currencyAccountIds]'");
            $rate     = $rate ?: ($currency['accuracy'] > 0 ? $currency['rate'] / $currency['accuracy'] : 1);
            $itemHtml .= <<<eof
<div class="account-item">
        <div class="account-item-title">$currency[code]：</div>
        <div class="account-item-value"><input name="moneyAsset" type="text" value="$money"></div>
</div>
<div class="account-item">
        <div class="account-item-title">汇率：</div>
        <div class="account-item-value"><input name="rateAsset" value="$rate" type="text"></div>
</div>
<input type="hidden" name="currencyHiddenId" value="$currency[id]">
<input type="hidden" name="currencyHiddenName" value="$currency[code]">
<input type="hidden" name="currenyMxId" value="$mxId">
eof;
        }
        $json['html'] = $itemHtml . $this->currencyJs();
        return json_encode($json, 320);
    }

    public function currencyJs()
    {
        return <<<eof
<script>
 $(window).off('keyup').keyup(function (event) {
        if (event.which === 13) {
            let accounting = $(".currency-assit")
            let isEmpty = false;
            accounting.find("input").each(function () {
                if (!$(this).val()){
                    isEmpty = true;
                }
            })
            if (!isEmpty && $(".currency-assit .account-item:last input").is(':focus')){
                $(".currency-assit  .confirm-button").trigger('click');
            }
            switchCurrenyInput(accounting.find("input:focus"))
        }
    })
</script>
eof;
    }

    public function getAssit()
    {
        $subject          = query('subject', "id = '" . $this->post('subjectId') . "'");
        $assistAccountIds = explode(',', $subject['assistAccountIds']);
        $subjectName      = $subject['code'] . ' ' . subjectClass::getName($subject['id']);
        $itemHtml         = '';
        foreach ($assistAccountIds as $val) {
            switch ($val) {
                case '客户':
                    $khid     = $this->post('khid');
                    $kehu     = query('kehu', "khid = '$khid'");
                    $text     = text(array('name' => 'clientId', 'data' => ['code' => $kehu['orderNo'], 'id' => $kehu['khid']], 'value' => clientProfileClass::getName($kehu['khid'], false, ' '), 'other' => "data-type='khid'", 'class' => 'assit-part', 'title' => '请选择'));
                    $itemHtml .= <<<eof
<div class="account-item">
        <div class="account-item-title">{$val}：</div>
        <div class="account-item-value">$text</div>
</div>
eof;

                    break;
                case '供应商':
                    $supplierId = $this->post('supplierId');
                    $supplier   = query('supplier', "id = '$supplierId'");
                    $text       = text(array('name' => 'supplierId', 'data' => ['code' => $supplier['code'], 'id' => $supplier['id']], 'value' => supplierClass::getName($supplier['id'], false, ' '), 'other' => "data-type='supplierId'", 'class' => 'assit-part', 'title' => '请选择'));
                    $itemHtml   .= <<<eof
<div class="account-item">
        <div class="account-item-title">{$val}：</div>
        <div class="account-item-value">$text</div>
</div>
eof;
                    break;
                case '员工':
                    $staffId  = $this->post('staffId');
                    $info     = query('staff', "stid = '$staffId'");
                    $text     = text(array('name' => 'staffId', 'data' => ['code' => $info['orderNo'], 'id' => $info['stid']], 'value' => implode(' ', array_filter([$info['orderNo'], $info['name']])), 'other' => "data-type='staffId'", 'class' => 'assit-part', 'title' => '请选择'));
                    $itemHtml .= <<<eof
<div class="account-item">
        <div class="account-item-title">{$val}：</div>
        <div class="account-item-value">$text</div>
</div>
eof;
                    break;
                case '部门':
                    $departmentId = $this->post('departmentId');
                    $info         = query('department', "id = '$departmentId'");
                    $text         = text(array('name' => 'departmentId', 'data' => ['code' => $info['orderNo'], 'id' => $info['id']], 'value' => implode(' ', array_filter([$info['orderNo'], $info['name']])), 'other' => "data-type='departmentId'", 'class' => 'assit-part', 'title' => '请选择'));
                    $itemHtml     .= <<<eof
<div class="account-item">
        <div class="account-item-title">{$val}：</div>
        <div class="account-item-value">$text</div>
</div>
eof;
                    break;
                case '项目':
                    $projectId = $this->post('projectId');
                    $info      = query('project', "id = '$projectId'");
                    $text      = text(array('name' => 'projectId', 'data' => ['code' => $info['orderNo'], 'id' => $info['id']], 'value' => implode(' ', array_filter([$info['orderNo'], $info['name']])), 'other' => "data-type='projectId'", 'class' => 'assit-part', 'title' => '请选择'));
                    $itemHtml  .= <<<eof
<div class="account-item">
        <div class="account-item-title">{$val}：</div>
        <div class="account-item-value">$text</div>
</div>
eof;
                    break;
                case '存货':
                    $materialId = $this->post('materialId');
                    $material   = query('material', "id = '$materialId'");
                    $text       = text(array(
                        'name'  => 'materialId',
                        'data'  => ['code' => $material['code'], 'id' => $material['id']],
                        'value' => implode('-', array_filter([$material['code'], $material['name']])),
                        'other' => "data-type='materialId'",
                        'class' => 'assit-part width300',
                        'title' => '请选择'
                    ));
                    $itemHtml   .= <<<eof
<div class="account-item">
        <div class="account-item-title">{$val}：</div>
        <div class="account-item-value">$text</div>
</div>
eof;
                    break;
                case '现金流':
                    $cashId   = $this->post('cashId');
                    $info     = query('cash', "id = '$cashId'");
                    $text     = text(array('name' => 'cashId', 'data' => ['code' => $info['code'], 'id' => $info['id']], 'value' => implode(' ', array_filter([$info['code'], $info['name']])), 'other' => "data-type='cashId'", 'class' => 'assit-part', 'title' => '请选择'));
                    $itemHtml .= <<<eof
<div class="account-item">
        <div class="account-item-title">{$val}：</div>
        <div class="account-item-value">$text</div>
</div>
eof;
                    break;
                default:
                    break;
            }

        }
        $isCurrency = '否';
        if ($subject['numAccount'] == '是' || $subject['currencyAccount'] == '是') {
            $isCurrency = '是';
        }
        $json['html'] = <<<eof
<div class="auxiliary-accounting">
    $itemHtml
    <div class="auxiliary-accounting-button">
        <input type="button" value="取消" onclick="hideAssetSelector()">
        <input type="button" value="确定" onclick="confirmAssist('{$this->post('mxId')}','$subject[id]','$isCurrency','$subjectName')" class="confirm-button">
    </div>
    {$this->assitJs()}
</div>
eof;
        return json_encode($json, 320);
    }

    public function assitJs(): string
    {
        return <<<eof
<script>
 $(window).off('keyup').on('keyup',function (event) {
        if (event.which === 13) {
            let accounting = $(".voucher-body .auxiliary-accounting")
            let isEmpty = false;
            accounting.find("input").each(function () {
                if (!$(this).val()){
                    isEmpty = true;
                }
            })
           
            if (!isEmpty && !$(".voucher-body .auxiliary-accounting input").is(':focus')){
                $(".voucher-body .auxiliary-accounting .confirm-button").trigger('click');
            }
            if (!isEmpty && $(".voucher-body .auxiliary-accounting input").is(':focus')){
                $(".voucher-body .auxiliary-accounting input").blur()
            }
        }
    })
$("input[name='clientId']").bigAutocomplete({
        // width:543,
        
        url:root + 'control/adIndex.html?cla=voucherEdit&fun=getClient',
        callback:function(data){
           $("input[name='clientId']").attr('data-id',data.id);
           $("input[name='clientId']").attr('data-code',data.code);
           switchAssetInput($("input[name='clientId']"));
        }
    });
  $("input[name='supplierId']").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=voucherEdit&fun=getSupplier',
        callback:function(data){
           $("input[name='supplierId']").attr('data-id',data.id);
           $("input[name='supplierId']").attr('data-code',data.code);
           switchAssetInput($("input[name='supplierId']"));
        }
    });
   $("input[name='staffId']").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=voucherEdit&fun=getStaff',
        callback:function(data){
           $("input[name='staffId']").attr('data-id',data.id);
           $("input[name='staffId']").attr('data-code',data.code);
           switchAssetInput($("input[name='staffId']"));
        }
    });
    $("input[name='departmentId']").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=voucherEdit&fun=getDepartment',
        callback:function(data){
           $("input[name='departmentId']").attr('data-id',data.id);
           $("input[name='departmentId']").attr('data-code',data.code);
           switchAssetInput($("input[name='departmentId']"));
        }
    });
     $("input[name='projectId']").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=voucherEdit&fun=getProject',
        callback:function(data){
           $("input[name='projectId']").attr('data-id',data.id);
           $("input[name='projectId']").attr('data-code',data.code);
           switchAssetInput($("input[name='projectId']"));
        }
    });
      $("input[name='materialId']").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=voucherEdit&fun=getMaterial',
        callback:function(data){
           $("input[name='materialId']").attr('data-id',data.id);
           $("input[name='materialId']").attr('data-code',data.code);
           switchAssetInput($("input[name='materialId']"));
        }
    });
       $("input[name='cashId']").bigAutocomplete({
        // width:543,
        url:root + 'control/adIndex.html?cla=voucherEdit&fun=getCash',
        callback:function(data){
           $("input[name='cashId']").attr('data-id',data.id);
           $("input[name='cashId']").attr('data-code',data.code);
           switchAssetInput($("input[name='cashId']"));
        }
    });
</script>
eof;

    }


    /**
     * 模糊查询现金流
     * @return bool|string
     */
    public function getCash(): bool|string
    {
        $val          = $this->post('keyword');//关键词
        $json['warn'] = 0;
        $where        = empty($val) ? "and 1=1" : "and (name like '%" . $val . "%' or code like '%" . $val . "%' or  concat(code,' ',name) like '%" . $val . "%')";
        $all          = find(array('table' => 'cash', 'where' => "coid = '" . self::$coid . "' $where order by code limit 100"));
        foreach ($all['array'] as $val) {
            $json['data'][] = array('title' => $val['code'] . " " . $val['name'], 'code' => $val['code'], 'id' => $val['id']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 模糊查询项目
     * @return bool|string
     */
    public function getProject(): bool|string
    {
        $val          = $this->post('keyword');//关键词
        $json['warn'] = 0;
        $where        = empty($val) ? "and 1=1" : "and (name like '%" . $val . "%' or orderNo like '%" . $val . "%')";
        $all          = find(array('table' => 'project', 'where' => "coid = '" . self::$coid . "' $where order by orderNo limit 100"));
        foreach ($all['array'] as $val) {
            $json['data'][] = array('title' => $val['orderNo'] . " " . $val['name'], 'code' => $val['orderNo'], 'id' => $val['id']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 模糊查询物料
     * @return bool|string
     */
    public function getMaterial(): bool|string
    {
        $val          = $this->post('keyword');//关键词
        $json['warn'] = 0;
        $where        = empty($val) ? "and 1=1" : "and (b.code like '%" . $val . "%' or b.name like '%" . $val . "%')";
        $all          = find(array(
            'table' => 'material as b',
            'field' => "b.id,b.code,b.model,b.name as materialName",
            'where' => "b.coid = '" . self::$coid . "'  $where order by b.code limit 100"
        ));
        foreach ($all['array'] as $val) {
            $json['data'][] = array('title' => materialClass::getName($val['id'], ''), 'code' => $val['code'], 'id' => $val['id']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 模糊查询客户
     * @return bool|string
     */
    public function getClient(): bool|string
    {
        $val          = $this->post('keyword');//关键词
        $json['data'] = [];
        $json['warn'] = 0;
        $where        = empty($val) ? "and 1=1" : "and (companyName like '%" . $val . "%' or orderNo like '%" . $val . "%' or  concat(orderNo,' ',companyName) like '%" . $val . "%')";
        $all          = find(array('table' => 'kehu', 'where' => "coid = '" . self::$coid . "'  $where order by orderNo limit 50"));
        foreach ($all['array'] as $val) {
            $json['data'][] = array('title' => $val['orderNo'] . " " . $val['companyName'], 'code' => $val['orderNo'], 'id' => $val['khid']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 模糊查询部门
     */
    public function getDepartment()
    {
        $val          = $this->post('keyword');//关键词
        $json['warn'] = 0;
        $where        = empty($val) ? "and 1=1" : "and (name like '%" . $val . "%' or orderNo like '%" . $val . "%'  or  concat(orderNo,' ',name) like '%" . $val . "%')";
        $all          = find(array('table' => 'department', 'where' => "1=1 $where order by time limit 50"));
        foreach ($all['array'] as $val) {
            $json['data'][] = array('title' => $val['orderNo'] . " " . $val['name'], 'code' => $val['orderNo'], 'id' => $val['id']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 模糊查询员工
     */
    public function getStaff()
    {
        $val          = $this->post('keyword');//关键词
        $json['warn'] = 0;
        $where        = empty($val) ? "and 1=1" : "and (name like '%" . $val . "%' or orderNo like '%" . $val . "%')";
        $all          = find(array('table' => 'staff', 'where' => "state != '离职' and workFlow = '已复核' $where order by time limit 100"));
        foreach ($all['array'] as $val) {
            $json['data'][] = array('title' => $val['orderNo'] . " " . $val['name'], 'code' => $val['orderNo'], 'id' => $val['stid']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 模糊查询供应商
     */
    public function getSupplier()
    {
        $val          = $this->post('keyword');//关键词
        $json['warn'] = 0;
        $where        = empty($val) ? "and 1=1" : "and (name like '%" . $val . "%' or code like '%" . $val . "%')";
        $all          = find(array('table' => 'supplier', 'where' => "coid = '" . self::$coid . "' and state = '启用' $where order by time limit 100"));
        foreach ($all['array'] as $val) {
            $json['data'][] = array('title' => $val['code'] . " " . $val['name'], 'code' => $val['code'], 'id' => $val['id']);
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     *选择模板
     * @return bool|string
     */
    public function template(): bool|string
    {
        $html   =
            select(array("name" => "templateType", "title" => "模板类型", 'option' => explode("，", para("voucherTemplateType")))) .
            text(array("name" => "code", "title" => "模板编码")) .
            text(array("name" => "templateName", "title" => "模板名称"));
        $button = "<input style='margin-left: 5px' onclick=\"chooseTemplate()\" type='button' class='searchSub' value='提交'>";
        $html   = $this->search($html);
        return $this->layer(array("title" => "选择模板", 'zindex' => 11, "height" => 600, "width" => 900, "html" => $html, "button" => $button));
    }

    /**
     *选择模板
     */
    public function templateSearch(): bool|string
    {
        $like  = [
            'templateName' => $this->post('templateName'),
            'templateNo'   => $this->post('code'),
        ];
        $equal = [
            'coid'         => self::$coid,
            'isTemplate'   => '是',
            'templateType' => $this->post('templateType'),
        ];
        $where = search(["like" => $like, "=" => $equal]);
        $page  = $this->page([
            "table" => "voucher",
            "where" => $where,
            "order" => "`time` ASC",
        ]);
        //获取表头
        $tr[] = ['', '模板编码', '模板名称', '模板类型',];
        //获取记录
        foreach ($page['array'] as $array) {
            $tr[] = array(
                "<input name='templateId' value='$array[id]' type='radio'>",
                $array['templateNo'],
                $array['templateType'],
                $array['templateName'],
            );
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }


    /**
     * 打印
     */
    public function printPage(): string
    {
        $maxLine    = 8;
        $id         = $this->get('id');
        $listId     = $this->get('listId');
        $listIds    = $listId ? explode(',', $listId) : [$id];
        $divHtml    = '';
        $voucherObj = new voucherClass();
        $printNum   = 0;
        foreach ($listIds as $index => $id) {
            $info        = query(self::table, " id = '$id'");
            $company     = query('company', "coid = '" . self::$coid . "'");//公司名称
            $stName      = self::findStaff($info['stid']);
            $auditName   = self::findStaff($info['auditStid']);
            $cashierName = self::findStaff($info['signStid']);

            $tempHtml      = '';
            $voucherWord   = query('voucher_word', "id = '$info[voucherWordId]'");
            $infoMx        = find(array('table' => 'voucher_detail', 'where' => "orderId = '$info[id]' order by rowList,list asc"));
            $maxVoucherNum = ceil(count($infoMx['array']) / $maxLine);
            $jieTotal      = $daiTotal = 0;
            $i             = -1;
            $selfPrintNum  = 0;
            foreach ($infoMx['array'] as $i => $array) {
                $assistName = $voucherObj->assitName($array);
                $jieMoney   = $array['direction'] == '借' ? self::centToYuan($array['money']) : 0;
                $daiMoney   = $array['direction'] == '贷' ? self::centToYuan($array['money']) : 0;
                $jieTotal   += $jieMoney;
                $daiTotal   += $daiMoney;
                $jieMoney   = $jieMoney == 0 ? '' : $jieMoney;
                $daiMoney   = $daiMoney == 0 ? '' : $daiMoney;
                $tempHtml   .= "
                             <tr class='have_border'>
                               <td>{$array['summary']}</td>
                               <td>{$assistName}</td>
                               <td>{$jieMoney}</td>
                               <td>{$daiMoney}</td>
                             </tr>
                            ";
                if ($i > 0 && $i % $maxLine == 7) {

                    $rmb  = self::num_to_rmb($jieTotal);
                    $line = $topLine = '';
                    if ($printNum % 2 == 0) {
                        $topLine = "<div data-op-type='new-page'></div>";
                        $line    = "<div class='dash-line'></div>";
                    }
                    $printNum++;
                    $selfPrintNum++;
                    $totalHtml = <<<eof
                <tr class='have_border'>
                    <td colspan='2'>合计：{$rmb}</td>
                    <td>{$jieTotal}</td>
                    <td>{$daiTotal}</td>
                </tr>
eof;
                    if (count($infoMx['array']) > $maxLine) {
                        $totalHtml = '';
                    }
                    $divHtml .= "
$topLine
  <div class='minHeight'>
                 <div>
                      <div class='printTitle' style='font-weight: bold;position: relative'>{$voucherWord['title']}<div class='file-text'>附件数：{$info['receiptNum']}</div></div>
                      <div class='printSubTitle'></div>
                 </div>
              <div class='table-top-title'><div style='flex: 1'>单位：{$company['name']}</div><div style='flex: 1'>单据日期：{$info['recordDate']}</div><div style='flex: 1'>凭证号：{$voucherWord['word']}-{$info['voucherNo']}-$selfPrintNum/$maxVoucherNum</div></div>
              <table class='printTable'  data-op-type='block-box'>
                <tbody class='nop-fill-box'>
               <tr class='have_border' style='font-weight: bold'>
                   <td style='min-width: 100px'>摘要</td>
                   <td>科目</td>
                   <td style='min-width: 90px'>借方</td>
                   <td style='min-width: 90px'>贷方</td>
                </tr>
                $tempHtml
                $totalHtml
                 <tr>
                    <td colspan='13'>
                         <div style='display: flex;flex-direction: row'>
                               <div style='flex: 1'>主管：</div>
                                <div  style='flex: 1'>审核：{$auditName}</div>
                                <div  style='flex: 1'>出纳：{$cashierName}</div>
                                 <div  style='flex: 1'>制单：{$stName}</div>
                         </div>
                    </td>
                </tr>
               </tbody>
              </table>
              </div>
              $line
            ";

                    $tempHtml = '';
                }
            }


            if (is_array($infoMx['array']) && $i % $maxLine < 7) {
                $max      = $i == -1 ? $maxLine : $maxLine - $i % $maxLine - 1;
                $tempHtml .= str_repeat("
                             <tr class='have_border'>
                               <td>&nbsp;</td>
                               <td></td>
                               <td></td>
                               <td></td>
                             </tr>
                            ", $max);
                $rmb      = self::num_to_rmb($jieTotal);
                $line     = $topLine = '';
                if ($printNum % 2 == 0) {
                    $line    = "<div class='dash-line'></div>";
                    $topLine = "<div data-op-type='new-page'></div>";
                }
                $selfPrintNum++;
                $divHtml .= "
           $topLine
          <div class='minHeight'>
                 <div>
                      <div class='printTitle' style='font-weight: bold;position: relative'>{$voucherWord['title']}<div class='file-text'>附件数：{$info['receiptNum']}</div></div>
                      <div class='printSubTitle'></div>
                 </div>
              <div class='table-top-title'><div style='flex: 1'>单位：{$company['name']}</div><div style='flex: 1'>单据日期：{$info['recordDate']}</div><div style='flex: 1'>凭证号：{$voucherWord['word']}-{$info['voucherNo']}-$selfPrintNum/$maxVoucherNum</div></div>
              <table class='printTable'  data-op-type='block-box'>
                <tbody class='nop-fill-box'>
               <tr class='have_border' style='font-weight: bold'>
                   <td style='min-width: 100px'>摘要</td>
                   <td>科目</td>
                   <td style='min-width: 90px'>借方</td>
                   <td style='min-width: 90px'>贷方</td>
                </tr>
                $tempHtml
                 <tr class='have_border'>
                    <td colspan='2'>合计：{$rmb}</td>
                    <td>{$jieTotal}</td>
                    <td>{$daiTotal}</td>
                </tr>

                 <tr>
                    <td colspan='13'>
                         <div style='display: flex;flex-direction: row'>
                               <div style='flex: 1'>主管：</div>
                                <div  style='flex: 1'>审核：{$auditName}</div>
                                <div  style='flex: 1'>出纳：{$cashierName}</div>
                                 <div  style='flex: 1'>制单：{$stName}</div>
                         </div>
                    </td>
                </tr>
               </tbody>
              </table>
              </div>
              $line
            ";
                $printNum++;
            }


        }


        $html  = <<<eof
                    <div id="content-box" style="display: none">
                    <!--    <div data-op-type="pendants">&lt;!&ndash; 定义页面部件（页眉/页脚/书签/水印背景等） &ndash;&gt;-->
                    <!--        <div class='pendant-title'>实发工资表</div>-->
                    <!--    </div>-->
                       {$divHtml}
                    </div>
                  <style>
                  .have_border td>div{min-height: 50px}
                  .file-text{position: absolute;top: 0;right: 0;font-size: 12px;font-weight: normal;margin-right: 10px;}
                   .footer-ul-parent{float: right;margin-right: 10px}
                  .footer-ul li{margin-top: 10px}
                  .table-top-title{
                    height: 30px;
                    line-height: 30px;
                    font-size: 14px;
                    margin-top: 20px;
                    display: flex;
                    flex-direction: row;
                  }
                  .table-top-title>ul>li{float: left;width: 250px;}
                  .printTable td{padding: 5px;font-size: 13px;}
                  .dash-line{width: 100%;border: 1px dashed;margin-top: 45px;margin-bottom: 70px}
                  .minHeight{min-height: 450px}
</style>
eof;
        $print = new printClass();

        return $print->showPrint($html);
    }


    /**
     * 获取摘要选项
     */
    public function getSummary()
    {
        $summaryTextArr = $this->post('summaryText') ?: [];
        $val            = $this->post('keyword');//关键词
        $json['warn']   = 0;
        $json['data']   = [];
        $where          = empty($val) ? "and 1=1" : "and b.summary like '%" . $val . "%'";
        $summaryTextArr = array_unique($summaryTextArr);
        foreach ($summaryTextArr as $val) {
            $json['data'][] = array('title' => $val);
        }
        $all = find(array('table' => 'voucher as a join voucher_detail as b on a.id = b.orderId', 'field' => "distinct b.summary", 'where' => "a.coid = '" . self::$coid . "' $where order by any_value(a.time) desc,any_value(b.list) desc limit 30"));
        foreach ($all['array'] as $val) {
            if (!in_array($val['summary'], $summaryTextArr)) {
                $json['data'][] = array('title' => $val['summary']);
            }
        }
        $json['warn'] = 2;
        return json_encode($json, 320);
    }

    /**
     * 增加科目
     * @return string
     */
    public function subjectTempAdd(): string
    {
        //币别
        $currencyOption = [];
        $all            = find(array('table' => 'currency', 'where' => "coid='" . self::$coid . "' order by time asc"));
        foreach ($all['array'] as $array) {
            $currencyOption[$array['id']] = $array['code'] . '(' . $array['name'] . ')';
        }
        $class   = [
            'hide',
            'hide',
            'hide',
        ];
        $checked = [
            '',
            '',
            '',
        ];
        array_pop(subjectClass::$assitOption);
        $all    = find(array('table' => 'subject', 'where' => "coid = '" . self::$coid . "'  order by list asc"));
        $resArr = componentClass::subjectSort($all['array'], true);
        $option = [];
        foreach ($resArr as $val) {
            $option[$val['id']] = $val['code'] . subjectClass::getName($val['id']);
        }
        $html = $this->layerEdit([
            "table"  => [
                [
                    must . '父级科目：' => select(['name' => 'pid', 'class' => 'width200', 'title' => '请选择', 'change' => 'getSubjectCode', 'option' => $option])
                ],
                [
                    must . "科目编码：" => text(["name" => "code"]),
                ],
                [
                    must . "科目名称：" => text(["name" => "name"]),
                ],
                [
                    must . "类别：" => "<span id='subjectType'>资产类</span>",
                ],
                [
                    must . '余额方向：' => radio(array('name' => 'direction', 'value' => ['借', '贷'], 'checked' => '借'))
                ],
                [
                    '外币核算：' => select(array('name' => 'currencyAccountIds', 'option' => $currencyOption, 'title' => '请选择外币符号'))
                ],
                [
                    "<label class='checkbox'><input name='numAccount' $checked[0] onclick=\"chooseBox(this,'numAccount')\" type='checkbox' value='是'><span></span>&nbsp;数量核算：</label>" => "<span id='numAccount' class='{$class[0]}'>计量单位&nbsp;" . text(array('name' => 'numAccountText', 'class' => 'width100')) . "</span>"
                ],
                [
                    "<label class='checkbox'><input  name='assistAccount' $checked[1] onclick=\"chooseBox(this,'assistAccount')\" type='checkbox' value='是'><span></span>&nbsp;辅助核算：</label>" => "<span id='assistAccount' class='{$class[1]}'>" . checkbox(array('name' => 'assistAccountIds', 'value' => subjectClass::$assitOption, 'checked' => [])) . "</span>"
                ],
            ],
            'hidden' => hidden(array('name' => 'state', 'value' => '启用')) . hidden(array('name' => 'type', 'value' => '资产类')) . $this->js(),//$voucherMx['id'] ? "<input type='button' class='button' style='background-color: #dadada' disabled value='已使用'>" :
        ]);
        //返回
        return $this->layer(array(
            "title"  => "编辑",
            "height" => 470,
            "width"  => 800,
            "html"   => $html,
            'button' => "<input onclick=\"subForm('voucherEditSubjectTempAddForm','" . root . "control/adIndex.html?cla=subject&fun=editEdit',function(){flushSubjuct()})\" type='button' class='button' value='确认提交'>"
        ));
    }


    /**
     * 根据父级科目生成编码
     * @return false|string
     */
    public function getSubjectCode()
    {
        $subject = query('subject', "id = '" . $this->post('id') . "'");
        if (empty($subject['id'])) {
            $json['warn'] = '未找到父级科目';
        } else {

            $assitOption = subjectClass::$assitOption;
            array_pop($assitOption);
            if ($subject['subjectSign'] == '现金流') {
                //现金科目加上现金流辅助选项
                $assitOption = array_merge($assitOption, ['现金流']);
            }
            $subjectObj      = new subjectClass();
            $assitOptionHtml = checkbox(array('name' => 'assistAccountIds', 'value' => $assitOption, 'checked' => []));
            $json['data']    = [
                'code'        => $subjectObj->subjectCode($subject['type'], $subject['id']),
                'subject'     => $subject,
                'assitOption' => $assitOptionHtml
            ];

            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }


    /**
     * 计算器
     * @return string
     */
    public function calculator(): string
    {
        $number   = $this->post('money') ?: 0.00;
        $textarea = $this->post('money') ?: '';
        $mxId     = $this->post('mxId');
        $type     = $this->post('type');
        $html     = <<<eof
<div class="calculator-container">
    <div class="calculator-box">
        <div class="calculator-title">
            <p>输入举例： (5+5)*2/(10-5)</p>
        </div>
        <div class="calculator-content">
            <textarea class="calculator-input" name="calculatorInput" id="calculatorInput">{$textarea}</textarea>
        </div>
        <div class="calculator-result">
            <span>计算结果：<span id="calculatorValue">$number</span></span>
        </div>
    </div>
    <div class="calculator-button">
     <span class="calculator-tip">提示：按回车键可快速保存结果</span>
     <button class="button button-confirm" type="button" id="calculatorBtn">确认</button>
     <input name="hiddenId" value="$mxId" type="hidden">
     <input name="hiddenType" value="$type" type="hidden">
    </div>
</div>
<script>
var regex = /^(\d+(\.\d+)?|\(.+\))(?:([+\-*/])(\d+(\.\d+)?|\(.+\)))*$/;
var singleSign = /^[+\-*\/]$/;
$(function (){
    var textarea = $("#calculatorInput");
    var calculatorValue = $("#calculatorValue");
    moveCursorToEnd()
    jisuan();

    $("#calculatorBtn").click(function () {
         saveRes($("[name='hiddenId']").val(),$("[name='hiddenType']").val())
    })
    textarea.off("keyup").on("keyup",function(ev){
        if (ev.keyCode === 13){
            saveRes($("[name='hiddenId']").val(),$("[name='hiddenType']").val())
        }
        jisuan();
    })
    
    function jisuan(){
        let input = document.getElementById('calculatorInput').value;
        // 去除空格
            input = input.replace(/\s/g, '');
           if (singleSign.test(input)){
              calculatorValue.html('0.00');
              document.getElementById('calculatorInput').value='';
              return false;
          }
          if (input === '' || !regex.test(input)) {
            calculatorValue.html('0.00');
             // console.log('格式错误')
            return false;
          }
       
         
          try {
           
            let val = eval(input); // 使用eval函数计算表达式的结果
             if (isNumber(val)){
                  calculatorValue.html(val.toFixed(2));
             }else{
                 calculatorValue.html('0.00');
             }
          } catch (error) {
              // console.log('计算错误')
             calculatorValue.html('0.00');
          }
    }
    /**
    * 将光标移动到文本域末尾
    */
    function moveCursorToEnd() {
        setTimeout(function() {
          var textarea = document.getElementById("calculatorInput");
            textarea.focus();
         
        // 将光标位置设置为文本域内容的长度
        textarea.selectionStart = textarea.value.length;
        textarea.selectionEnd = textarea.value.length;
        },300)
    }
    function isNumber(value) {
      return /^-?\d+(\.\d+)?$/.test(value);
    }
})


</script>

<style>
.calculator-button{padding: 10px 40px}
.calculator-title{margin-top: 30px;padding: 0 40px}
   .calculator-content {padding: 5px 40px 20px;}
   .calculator-input {
      resize: none;
    outline: none;
    font-size: 22px;
    line-height: 30px;
    padding: 14px;
    width: 100%;
    height: 109px !important;
    box-sizing: border-box;
    font-weight: 700;
  }
  .calculator-result{
      text-align: right;
      border-bottom: 1px solid #e6e6e6;
      padding: 10px 40px 30px;
  }
  #calculatorValue{
        line-height: 33px;
        font-size: 24px;
        font-weight: 700;
  }
  .button-confirm{width: 80px;float: right;}
  .calculator-tip{vertical-align: sub}
</style>
eof;

        //返回
        return $this->layer(array("title" => "计算器", "height" => 385, "width" => 800, "html" => $html, "button" => false));
    }

    /**
     * 数字格式化
     * @param $number
     * @return string
     */
    public static function splitNumber($number): string
    {
        $digits = str_split(strrev($number));
        $output = '';
        $index  = 0;
        foreach ($digits as $k => $digit) {
            if ($k == 1) {
                $output = '<div class="format-line pink">' . $digit . '</div>' . $output;
            } elseif ($k == 4 || $k == 7) {
                $output = '<div class="format-line l-blue">' . $digit . '</div>' . $output;
            } else {
                $output = '<div class="format-line">' . $digit . '</div>' . $output;
            }
            $index++;
        }
        for ($index; $index < 11; $index++) {
            if ($index == 1) {
                $output = '<div class="format-line pink"></div>' . $output;
            } elseif ($index == 4 || $index == 7) {
                $output = '<div class="format-line l-blue"></div>' . $output;
            } else {
                $output = '<div class="format-line"></div>' . $output;
            }
        }
        return $output;
    }
}

